UNIT I
PROGRAMMING PARADIGM
Program :
A sequence of instructions s communicated to the computer to solve a problem, this sequence of instructions is called program
Programming languages :
To communicate these instructions with the systems, programming languages are developed.
Hardware and software :
Hardware – “Physical Structure of the computer”
Software – “Programs needed for the computer to do jobs”
Types of Software:
i) Application Software – Set of programs necessary to solve the problems, written by the user of a computer. (eg – Finding factorial of a number)
ii) System Software – Written by the computer manufactures related to that computer mechanisms.(eg – compiler, interpreter, loader). Set of programs which communicate the application software to the computer.
Types of programming Languages:
i) Low Level language:
As a computer does everything in binary form, the programs t be given to a computer must be given only in a binary form ( 0&1 alone must be used). This program said to be in machine language.
ii) High Level language:
Writing low level program is difficult –to overcome this high level languages were developed. (eg) BASIC, FORTRAN, PASCAL, COBOL, C.
iii) Assembly Level Language:
Assembly Level Languages uses mnemonic codes
Eg : ADD A,B
Above Statement represents the addition of Value of Accumulator and value of B register. The resultant contents are stored in Accumulator itself.
Styles of Programming:
Each programming language enforces a particular style of programming. The way of organizing information is influenced by its style of programming and it is known as programming paradigm.
First Generation Programming Languages:
· From 1954 – 1958
· It is also called monolithic programming
· It is developed for simple application purpose
· You will have expressions, expressions have operands and operators
· No support for subprograms
· Data is globally available
· Example are : FORTRAN –I , ALGOL 58,Flowmatic
Sequence of statements (Program)
Global Data
Second Generation Programming Languages :
· From 1959 – 1961
· Allows subprograms (functions, procedure, subprograms)
· Partial hiding information(through subprogram)
· Sharing the data by many subprograms breaks the data hiding principle
· Example are : FORTRAN II, ALGOL 60, COBOL
SubProgram
SubProgram
SubProgram
Global Data
Third Generation Programming Languages:
· From 1962 -1970
· It is also called Structured Programming
· Uses sequential code
· Introduction of scope of variables
· Allows Subprograms
Module 1
Module 2
Module 3
Global Data
Nested Subprograms
Sub
Program
Sub
Program
Sub
Program
Sub
Program
Local Variables may exist in the subprograms
Different between Structured Programming and Object Oriented Programming :
S.No
Structured Programming
Object Oriented Programming
1.
Top-down approach
Bottom-up approach
2.
Focus is on algorithm & control flow
Focus is on object model or data
3.
Program is divided into a no.of sub modules or functions or procedures
Program is organized by having a no.of classes and objects
4.
Functions are independent of each other
Each class is related in a hierarchical manner
5.
No designated receiver in the function
There is a designated receiver for each message passing
6.
Views data and functions as two separate entities
Views data and functions as a single entity
7.
Maintenance is costly
Maintenance is relatively cheaper
8.
Software reuse is not possible
Helps in software reuse
9.
Function call is used
Message passing is used
10.
Function abstraction is used
Data abstraction is used
11.
Algorithm is given importance
Data is given importance
12.
Solution is solution-domain specific
Solution is problem-domain specific
13.
No encapsulation . Data and function are separate
Encapsulation packages . code & data altogether. Data & functionalities are put together a single entity
14.
Relational between programmer & program is emphasized
Relational between programmer user is emphasized
15.
Data driven technique is used
Is driven by delegation of responsibilities.
BASICS CONCEPTS OF OOP
OOP is a method of implementation in which programs are organized as co-operative collections of objects, each of which represents an instance of some class & whose classes are all members of a hierarchy of classes united through the property called inheritance.
Concepts of OOP:
Objects
Classes
Data abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message Passing
Classes and objects :
Object is anything having crisply defined conceptual boundaries.
Eg: Book, pen, train, employee etc...
Not an example : Beauty, river, sky etc…
An object has
- States or properties
- Operations
- Identity
Properties :- Properties maintain the internal state of object
Operations:- Operations provide the appropriate functionality to the object
Identity:- Identity differentiates one object from the other.
Class is a collection of objects . (or) The class is a prototype or blueprint or model that defines different features. A feature may be a data or an operation. Data are represented by instance variables or data variables in a class. The operations are also known as methods or functions.
Object Model is defined by the means of classes and objects.
1. Object is an instance of class datatype
2. It gives life to a class
3. It is a container for storing its features
4. It occupies memory location
5. It can be manipulated Class Object
Class is a datatype
It generates object
It is the prototype or model
It doesn’t occupy memory location
IT can’t be manipulated because it is
not available in the memory
Mapping real world entity to object oriented programming:
Entity
Properties
Operations
Data
Functions
Real World Abstraction OOP Class
Different styles of representing an object:
Object Name
Attribute 1
:
:
:
Attribute N
Operation 1
:
:
Operation N
Oprn1
OprnN
Oprn2
Attr 1
:
AttrN
Object Name
Attribute 1
:
:
:
Attribute N
Operation1
Operation2
Operation3
Oprn – operation, Attr - Attribute
Encapulation :
Is a mechanism that associates the data and code that manipulates the data and keep them safe from external interference and misuse.
Data Abstraction :
Creating new data types using encapsulated items that are suited to an application to be programmed is called as data abstraction.
Abstract Data Types(ADT) :
The data types created by data abstraction are called as abstract data types.
Inheritance :
Is a process of deriving a new class from the existing class without modifying it.
Advantage :
· Adding new features to the system without modifying the existing one.
· Easy to enhance the system
· Reusability of code.
Differentiate data abstraction and encapsulation.
S.No
Data abstraction
Encapsulation.
1
Separates interface and implementation
Groups related items into one group
2
Provide access to a specific part of data
Hides the data and the user cannot access the same directly
3
Defined as a data type called class which separates interface from implementation
Packages data and functionality and hides the implementation details
Polymorphism :
Ability to take more than one form. Two types :
· Compile time polymorphism(Static or Early binding) –Linking done at compile time. Eg: Function overloading, Operator Overloading
· Runtime Polymorphism(Dynamic or Late binding) - Linking done at run time.
Eg : Virtual Function
Message Communication :
Objects can communicate(interact) with each other through functions. Message passing involves specifying the name of an object, name of the function(message) and information to be sent. It is similar to function call.
Example : student.marks(rollno);
Where student – object marks – message rollno - information
Benefits or advantages or Merits of OOP:
OOP offers several benefits to both the program designer and user.
· Extend the program without modifying the existing one using the concept of inheritance provides reusability of code.
· The standard library can be extended by users reduces the amount of code and allow us to build reliable programs.
· Data hiding allow us to build secure programs.
· Easily partitioned a large project into small module and handled easily.
· Object oriented systems can be easily upgraded from small to large systems.
· Software complexity can be easily managed.
· Suitable for solving complex problems.
· Easily map the real world problems.
· Software maintenance cost reduced.
· Software quality improved.
Applications of OOP :
The areas make use of OOP are real time systems, Digital Image Processing, Neural networks, Pattern Recognition, AI and expert systems, Mobile computing, Parallel Computing, DBMS, Data warehousing and Data Mining, Object oriented databases.
Structure of a C++ program :
Include Files
Class Declarations
Member Function Definitions
Main Function Program
The 4 sections may be placed in separate or same file.
• Organize the program into 3 separate files
1. Class Declarations
2. Member Function Declarations
3. The main function which includes previous 2 files.
Advantage :
• Abstracts the implementation details from other users.
• Resembles client-server model
•
Member Function
Class Definition
Server
Client
Main FunctionDifferent phases of C++ program execution.
· Creating a Program
· Compiling a Program
· Linking the program with functions that are needed from the C++ library
· Executing the program
FUNDAMENTALS OF C++
Introduction :
• Object Oriented Programming Language
• Developed by Bjarne Stroustrup at AT & T Bell Laboratories in the year
1980
• Extension of C
• C with OO concepts
• Called as C with Classes
Applications C++ :
• Able to handle very large programs
• Suitable for developing editors, compilers, databases, communication
systems and complex real world problems.
• Able to map real world problem properly.
• Programs are easily maintainable and expandable.
Character set :
• All Uppercase and Lowercase Alphabets A..Z & a..z
• All digits from 0..9
• Special characters
TOKENS :In a C++ program the smallest individual units are known as C++ Tokens
Eg : constants, identifiers, keywords, operators, etc.,
Identifiers :
• Every word in C++ program can be either Identifier or Keyword
• Identifier is a name given to Variables, Functions, Constants,
Symbolic constants
RULES FOR IDENTIFIERS :
• Consists of only letters,digits or underscore
• First character must be an alphabet
• Any length - Only first 31 characters are significant
• Cannot use a keyword
• Must not contain white space
Example :
Sum, avg, total, mark, a, b
Keywords :
• Built in words--- Fixed Meaning ( These meanings can’t be
changed.)
• Written in lowercase letters
Example:
void, case, if, int ,float ,else, while
Data Types :
C++ supports three classes of datatypes:-
· •
Primary (or fundamental ) or built-in datatypes
· •
Derived datatypes
· User-defined datatypes
Primary (or fundamental ) or built-in datatypes :
int, float, double, char, short int, long int, signed short int, unsigned
short int etc.,
Derived datatypes
• Array
• Function
• Pointer
User-defined datatypes
• Structure
• Union
• Class
• Enumeration
VARIABLES :
· Entity whose value can be changed during program execution.
· All variables must be declared before it can be used in the program.
Syntax:
datatype variable name;
Example :
int a,b,sum;
float x;
char c, s[10];
DYNAMIC INITIALIZATION OF VARIABLES:
It is also possible in C++ to declare a variable at the point of their first usage.
Example :
float avg = sum/n;
for(int i = 0 ; i < 10 ; i++)
OPERATORS
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• Bitwise Operators
• Special Operators
Arithmetic Operators :
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulo Division
Example :
x + y, a - b, a * b, f / s, f % s
Relational Operators :
< : Less than
> : Greater than
<= : Less than or equal to
>= : Greater than or equal to
!= : Not equal to
Example :
x <> b, a <= b, f >= s, f != s
Logical Operators :
&& : Logical AND
|| : Logical OR
! : Logical NOT
Example :
a > b && x == 10;
a < b || a < n
!(x >= y)
Assignment Operators :
•Assignment Opeartor
•Compound Assignment Operators
Assignment Operator :
= : Assign value to a variable
Syntax :
variable = expression;
Example :
a = 100;
b = z + 10 *a;
COMPOUND ASSIGNMENT OPERATORS :
Syntax :
variable opeartor = expression/constant
x = x + 10 can be written as x + = 10;
operator : can be any arithmetic, relational, logical operator.
Compound Assignment Operators :
+=, -=, *=, /=, %=, &=, |=, <<=, >>=
Example :
A+=exp; a-=exp; a*=exp;
INCREMENT AND DECREMENT OPERATORS :
Increment Operator : ++
Pre Increment - Eg: ++a
Post Increment – Eg: a++
Example : int a=10, b=10;
a = ++b assigns b = 11, a=11
a= b++ assign a = 10, b=11
Decrement Operator : --
Pre Decrement - Eg: --a
Post Decrement – Eg: a--
CONDITIONAL OPERATOR
Ternary operator pair ?:
Syntax :
exp1 ? exp2 : exp3
True False
Example :
if (a>b)
x=a;
else x=b;
Can be written as
x=(a>b) ? a : b
BITWISE OPERATORS
Operator Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
<<
Shift Left
>>
Shift Right
~
One’s complement
SPECIAL OPERATORS :
• Comma operator
• Size of operator
• Pointer operators
• Member selection operator
COMMA OPERATOR :
• Used to link the related expressions together
• Used in for loops and while loops
Example 1: swapping two numbers
t = x, x = y, y = t;
Example 2 :
a = (x=10,y=5,x+y);
Takes value from left to right manner:
1.Assigns 10 to the variable x
2.Assigns 5 to y
3.And finally assigns 15 to the variable a
Sizeof operator :
• Is a compile time operator
• It returns the number of bytes that the operand occupies
• Operand may be a variable, a constant or a datatype
Syntax :
sizeof(data-type);
sizeof(variable);
Example :
M=sizeof(sum) returns 2 if sum is int
N=sizeof(long int) returns 4
a =sizeof(float) returns 4
a =sizeof(double) returns 8
a =sizeof(long double) returns 10
Additional Operators in C++ :
<< - Insertion operator
>> - Extraction operator
:: - Scope resolution operator
::* - Pointer-to-member declarator
->* - Pointer-to-member operator
.* - Pointer-to-member operator
new - Memory allocation operator
delete - Memory release operator
endl - Line feed operator
setw - Field width operator
Scope resolution operator ::
• Used to access the global variable.
Example :
#include
int a = 10;
main()
{
int a= 50;
a = a+100;
cout<cout<<::a;
}
Output :
150
10
EXPRESSIONS
• Combination of operands and operators
Example :
a*b-c
(m+n)*(x+y)
a*b/c
3*x*x+2*x+1
TYPE CONVERSION :
• Implicit or AutomaticType conversion
• Explicit Type Conversion
Implicit Type conversion :
Compiler performs type conversion of data items when an expression consists of data items of different data types.
Explicit Type Conversion :
Syntax:
(data-type) expression;
(data-type) variable-name;
or
data-type(expression);
data-type(variable-name);
Example:
int a,b;
float c;
c=a/b;
c=(float) a/b;
CONSTANTS:
• Fixed values that do not change during the execution of a program.
Types of constants:
•Numeric constants :
1) Integer Constants 2) Real Constants
•Character constants:
1) Single character 2) String constants
NUMERIC CONSTANTS :
INTEGER CONSTANTS: Sequence of digits.
Types of Integer Constants:
Decimal Integer constant: consists of a set of digits.(0 through 9 preceded by an optional + or - sign.
Eg : 1234 , -3215, 0, 65872, +77
• Embedded spaces, commas and non digit characters are not permitted between digits.
23,860 23 860 $555 - Not Permitted
Octal Integer Constant:
•Combination of digits (0 through 7 with a leading 0).
Eg : 088 , 0 , 0564, 0115
Hexadecimal Integer Constant:
•Sequence of digits (0 through 9, A through F with a leading 0x,0X)
Eg : 0X3, 0x3, 0XDEF, 0x8E
REAL CONSTANTS
•Numbers containing fractional parts
•These numbers are called real (or floating point) constants.
Eg : 0.0083 -0.78 475.75 +36.0
215. .95 -.71 +.5
Real number may be expressed in exponential (or scientific notation).
Syntax:
mantissa e exponent
•Mantissa- real number expressed in decimal notation (or) an integer.
CHARACTER CONSTANTS
Single character constant:
•contains a single character enclosed within a pair of single quote marks.
Eg : ‘5’ ‘X’ ‘;’ ‘ ‘
‘5’– not the same as 5
printf(“%d”,’a’);
o/p: 97(ASCII value of a =97)
STRING CONSTANTS:
• Sequence of characters enclosed in double quotes.
• Characters may be letters, numbers, special characters and blank space
Eg : “hai!” “1981” “WELLDONE” “X” “8+7”
“X” (does not have an equivalent integer value) not equal to ‘X’ (have an equivalent integer value)
Enumerated Data Types :
•User defined data type.
•Values ranges over a finite set of identifiers called as enumeration constants.
Syntax :
enum identifier {set of constants};
Example :
enum color {red, blue, green};
color a,b;
b = red; a = blue;
cout << a << b << c; displays 1 0
PREPROCESSOR :
It is a program that processes the source code before it passes through the compiler.
PREPROCESSOR DIRECTIVES:
It is placed in the source program before the main function.
3 CATEGORIES:
• Macro substitution directives
• File Inclusion directives
• Compiler Control directives
MACRO SUBSTITUTION DIRECTIVES
Identifier in the program is replaced by a predefined value(string). Also called as symbolic constant declaration.
Syntax:
#define identifier(sym. Const. name) value
Example for Simple Macro Substitution
#define PI 3.14
#define NAME “XXX”
#define SUM 2*3-1
Argumented Macro Substitution(Macro function) :
Syntax:
#define identifier(f1, f2,…,fn) string
Example :
#define CUBE(x) (x*x*x)
In program:--
The above example is expanded as
volume=CUBE(side); --- > (side*side*side)
UNDEFINING A MACRO:
#undef identifier
FILE INCLUSION DIRECTIVES
SYNTAX:
#include
Searched only in the standard directory.
Example :
#include
SYNTAX:
#include “filename”
Preprocessor inserts the entire contents of filename into the source code of the program. Search for the file is made first in the current directory and then in the standard directories.
Example :
#include “sum.cpp”
Operator Precedence and Associativity
:
Precedence of operator :
• Specifies which operator can be evaluated first.
• Each operator in C++ has a precedence associated with it.
Precedence of arithmetic operators :
High priority * / %
Lower priority + -
Example :
Evaluate x=a-b/3+c*2-1;
Evaluate y=a-b/(3+c)*(2-1);
Evaluate z=a-(b/(3+c)*2)-1;
ASSOCIATIVITY :
•Specifies the direction - (from left to right (or) right to left) in which the expression is evaluated, while using the particular operator.
•It is also differs from operator to operator.
CONTROL STATEMENTS
BRANCHING STATEMENTS
• If Statement
• If-Else Statement
• Switch Statement
• Goto Statement
• Break Statement
• Continue Statement
LOOPING STATEMENTS
• For Loop
• While Loop
• Do-while Statement
IF STATEMENT
: used to control the sequence of the execution of statements.
if(test-expression)
statement;
if(test-expression)
{
statement 1;
statement 2;
}
Example :
if (x == 100){ cout << "x is "; cout << x;}
IF-ELSE STATEMENT
: Some actions are performed even though the test expression fails.
if(test-expression) if(test-expression)
{ statement 1;
statement 1; else
statement 2; statement 2;
}
else
{
statement 3;
statement 4;
}
statement 5;
Example : if (x == 100) cout << "x is 100";else
cout << "x is not 100";
ELSE IF STATEMENTS :
used when there are multiple conditions and different actions to be taken under each condition. (Multi-way decision)
if(test-expression 1)
statement 1;
else if(test-expression 2)
statement 2;
else if(test-expression 3)
statement 3;
else
statement 4;
Example :
if (x > 0) cout << "x is positive";else if (x < 0) cout << "x is negative";else
cout << "x is 0";
FOR LOOP
: It is used to execute statement a fixed number of times.
for(initialization;condition;updation)
statement;
for(initialization;condition;updation)
{
statement 1;
statement2;
}
statement;
// countdown using a for loop#includeusing namespace std;int main (){ for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!"; return 0;}
Output :10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
WHILE LOOP
: It is used when the number of iterations to be performed are not known in advance.
while(expression)
{
statement 1;
statement 2;
}
statement;
Example: // custom countdown using while #includeusing namespace std; int main (){ int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!"; return 0;}
Output :Enter the starting number > 88, 7, 6, 5, 4, 3, 2, 1, FIRE!
DO-WHILE LOOP :
It executes the body of a loop atleast once.
Syntax : do
{
statement 1;
statement 2;
}while(condition);
statement;
Example : // number echoer #includeusing namespace std; int main (){ unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0;}
Output :
Enter number (0 to end): 12345You entered: 12345Enter number (0 to end): 160277You entered: 160277Enter number (0 to end): 0
You entered: 0
BREAK STATEMENT :
It terminates the execution of loop and the control is transferred to the statement immediately following the loop.
for(i=0;i<20;i++) while(expr)
{ {
…. …..
if(condition) if(condition)
break; break;
…. …..
} }
statement; statement;
Example :#include int main (){ int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0;} Output :10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
SWITCH STATEMENT
: used to replace multiple if-else statement.
switch(test-variable)
{
case v1:
statements;
break;
case v2:
statements;
break;
…..
default :
statements;
break;
}
statement;
Example :
switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }
CONTINUE STATEMENT
:It skips the remainder of the current iteration and initiates the execution of the next iteration.
for(j=0;j<20;j++) while(expr)
{ {
….. …..
if(expr) if(expr)
continue; continue;
…. ….
} }
Example :
#includeusing namespace std; int main (){ for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!"; return 0;} Output :10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
ARRAYS
-Set of data items of the same datatype under a common name.
-They are popularly known as Subscripted Variable.
Array Definition(Single dimensional Array) :
Syntax: datatype array_name[array_size];
Example:
int age[5];
char name[20];
Accessing Array Elements:
•It can be accessed by using array index or subscript which ranges from 1 to n.
Syntax:
array_name[index];
Example:
int age[5];
cout< Note: There is no array bound validation
Array Initialization – at Definition
Syntax:
datatype array_name[size]={list of values separated by comma};
Example:
int age[5]={10,1,50,20,11};
int age[]={10,1,50,20,11};
Array Initialization – Not in Definition
-using For loop ,while or do-while loop
Example 1 :
int age[5];
for(int i=1;i<=5;i++)
cin>>a[i];
Example 2 : // arrays as parameters #includeusing namespace std; void printarray (int arg[], int length) { for (int n=0; n
Output :5 10 152 4 6 8 10
Two Dimensional Arrays
Syntax:
array_name[row_index][column_index];
Example:
int a[3][3];
cout<
Initialization at Definition
Syntax
datatype array_name[row_size][col_size]={
{elements of first row},
{elements of second row},
……….,
{elements of Nth row}
};
STRINGS
It is represented as an array of characters and the end of the string is marked by the NULL (‘\0’) character.
String constants : Are enclosed by double quotes.
Eg. cout<<“Welcome to SIT”;
STRING DECLARATION :
Syntax
char array_name[size];
Example:
char name[30];
cin>>name;
String Initialization:
Syntax:
char array_name[size]=“string”;
Example:
char month[10] = “April”;
STRING MANIPULATIONS
#include
-strlen(string_variable);
-strcat(string_variable1,string_variable2);
-strcpy(string_variable1,string_variable2);
-strcmp(string_variable1,string_variable2);
-strlwr(string_variable);
-strupr(string_variable);
Examples:
char name[20]=“hello”;
cout<
char name[20]=“rama”;last[20]=“world”;
int i;
cout< cout< i=strcmp(name,last);
cout<
MANIPULATORS
Manipulators are operators used to format the output display. To include the file #include to use manipulators in the program. The manipulators are“\n” and “\t”, endl ,setw(),setbase(), setfill(), setprecision(), flush()
Endl : Used to feed one line.
Example : int a = 123, m = 21, n = 3; cout << a << endl << m << endl << n;
Output :
123
21
3
Setw(): Used to set the field width and used to display the output in right alignment form.
Example : int a = 123, m = 21, n = 3;
cout << setw(5) << a << endl << setw(5) < Output :
123
21
3
setbase() : Used to set the base.
Example : int value = 15; cout << setbase(10) << value << endl;
cout << setbase(8) << value << endl; cout << setbase(16) << value << endl;
Output :
15
17
f
setfill() : Used to fill the unused space created using setw() with specified character.
Example : int a = 123, m = 21, n = 3; cout << setfill(‘*’);
cout << setw(5) << a << endl << setw(5) < Output :
**123
***21
****3
setprecision() : Used to control the no. of digits after decimal point.
Example : float a=12.3456; cout << a << endl;
cout << setprecision(2) << a << endl; cout << a;
Output :
12.3456
12.35
12.35
flush() : Used to empty the output buffer.
Syntax : cout.flush();
Reference variable :
· alias (alternative name) for a previously declared variable.
· After that the 2 names can Provides an be used to access that variable.
Syntax : data-type var.name;
data-type & ref-name = var.name;
Example :
float total = 100;
float & sum = total; à sum and total = 100
total = total + 50; à sum and total = 150
sum = 0; à sum and total = 0
Need :
· Reduces the complexity of using pointer variable.
· Do the same function but not access the address.
FUNCTIONS
Elements of Function :
1. Function Prototype
2. Function Parameters
3. Function Definition
4. Function Call
5. return statement
Function Prototypes:
•Additional feature added to C++
•It provides the following information to the complier.
1.The name of the function
2.The type of the value returned by the function
3.The no. and type of arguments passed to the function
•When the function call is encountered, the complier checks the function call with its prototype to ensure that correct arguments are used if not then the compiler informs the user about that.
Syntax :
ret. type fun.name(arg1, arg2,...argn);
Example :
Function Prototype :
float volume (int, float);
Function Definition :
float volume (int x, float y)
{ float a;
body of the function;
return a;
}
Function call :// function example#includeusing namespace std; int addition (int a, int b){ int r; r=a+b; return (r);} int main (){ int z; z = addition (5,3); cout << "The result is " << z; return 0;}
Output :
The result is 8
Parameter Passing
• call by Value
• call by Address
•
call by Reference
Pass by Value :
•Updation of an argument within the function not affect the main function
Example :
float volume (int, float); //Fn prototype
float volume (int x, float y) //Fn definition
{
float a;
a = x * y;
x= x + 10; y = y + 100;
cout< return a;
}
void main
{ int m =1, n = 2;
L = volume(m,n); //Function call
cout < Pass by Address :
•Passing address instead of value then the updation of an argument within the function affect the main function also.
Example :
float volume (int *, float *); //Fn prototype
float volume (int *x, float *y) //Fn definition
{ float a;
a = *x * *y;
*x= *x + 10; *y = *y + 100;
cout<<*x<<*y;
return a;
}
void main
{ int m =1, n = 2;
L = volume(&m,&n); //Function call
cout <
Pass by Reference :
Updation of an argument within the function affect the main function also because instead passing address only value can be passed but we create a reference to that variable in the function
Example 1: // passing parameters by reference #includeusing namespace std; void duplicate (int& a, int& b, int& c){ a*=2; b*=2; c*=2;} int main (){ int x=1, y=3, z=7; duplicate (x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return 0;} Output :x=2, y=6, z=14
Disadv of function:
•When the program executes the function call instruction the CPU stores the address of the instruction following the function call, copies the arguments of the function call onto the stack and finally transfers control to the specified function.
•The CPU then executes the function and stores the returned value in the predefined memory address and returns control to the calling function.
•It is a overhead in the execution time of the program
•Sometimes the execution of program takes lesser time than the context switch time..
INLINE FUNCTIONS
• C++ provide a alternative in the form of Inline functions.
• Inline functions are those whose function body is inserted in place of the function call statement during the compilation process. There is no context switch overhead.
• Similar to macro of C.
Disadv of macro : They are not functions then usual error checking does not occur during compilation
•Inline function enjoy both the flexibility and power offered by normal functions and macro functions.
Syntax :
inline ret.type fun.name(arguments)
{
Body of the function
};
Example 1 :
#include
Inline void hello()
{
cout<<”hello”< }
int main()
{
hello();
cin.get();
return 0;
}
Output : hello
Example 2:
//To multiply two numbers
#include
inline float mul(float x, float y)
{return(x*y);}
void main()
{
float a,b;
cout<<“Enter 2 numbers”;
cin>>a>>b;
cout<cout<< “100 * 15 =“< }
Output :
Enter 2 numbers 5 3
5*3=15
100*15=1500
DEFAULT ARGUMENTS
•C++ allow us to call the function without specifying all the arguments defined in the function prototype.
•The compiler assigns a default value to the argument which does not have a matching argument in the function call.
•The default values are specified in the function prototype.
Example :// default values in functions#includeusing namespace std; int divide (int a, int b=2){ int r; r=a/b; return (r);}int main (){ cout << divide (12); cout << endl; cout << divide (20,4); return 0;}
PROGRAMMING PARADIGM
Program :
A sequence of instructions s communicated to the computer to solve a problem, this sequence of instructions is called program
Programming languages :
To communicate these instructions with the systems, programming languages are developed.
Hardware and software :
Hardware – “Physical Structure of the computer”
Software – “Programs needed for the computer to do jobs”
Types of Software:
i) Application Software – Set of programs necessary to solve the problems, written by the user of a computer. (eg – Finding factorial of a number)
ii) System Software – Written by the computer manufactures related to that computer mechanisms.(eg – compiler, interpreter, loader). Set of programs which communicate the application software to the computer.
Types of programming Languages:
i) Low Level language:
As a computer does everything in binary form, the programs t be given to a computer must be given only in a binary form ( 0&1 alone must be used). This program said to be in machine language.
ii) High Level language:
Writing low level program is difficult –to overcome this high level languages were developed. (eg) BASIC, FORTRAN, PASCAL, COBOL, C.
iii) Assembly Level Language:
Assembly Level Languages uses mnemonic codes
Eg : ADD A,B
Above Statement represents the addition of Value of Accumulator and value of B register. The resultant contents are stored in Accumulator itself.
Styles of Programming:
Each programming language enforces a particular style of programming. The way of organizing information is influenced by its style of programming and it is known as programming paradigm.
First Generation Programming Languages:
· From 1954 – 1958
· It is also called monolithic programming
· It is developed for simple application purpose
· You will have expressions, expressions have operands and operators
· No support for subprograms
· Data is globally available
· Example are : FORTRAN –I , ALGOL 58,Flowmatic
Sequence of statements (Program)
Global Data
Second Generation Programming Languages :
· From 1959 – 1961
· Allows subprograms (functions, procedure, subprograms)
· Partial hiding information(through subprogram)
· Sharing the data by many subprograms breaks the data hiding principle
· Example are : FORTRAN II, ALGOL 60, COBOL
SubProgram
SubProgram
SubProgram
Global Data
Third Generation Programming Languages:
· From 1962 -1970
· It is also called Structured Programming
· Uses sequential code
· Introduction of scope of variables
· Allows Subprograms
Module 1
Module 2
Module 3
Global Data
Nested Subprograms
Sub
Program
Sub
Program
Sub
Program
Sub
Program
Local Variables may exist in the subprograms
Different between Structured Programming and Object Oriented Programming :
S.No
Structured Programming
Object Oriented Programming
1.
Top-down approach
Bottom-up approach
2.
Focus is on algorithm & control flow
Focus is on object model or data
3.
Program is divided into a no.of sub modules or functions or procedures
Program is organized by having a no.of classes and objects
4.
Functions are independent of each other
Each class is related in a hierarchical manner
5.
No designated receiver in the function
There is a designated receiver for each message passing
6.
Views data and functions as two separate entities
Views data and functions as a single entity
7.
Maintenance is costly
Maintenance is relatively cheaper
8.
Software reuse is not possible
Helps in software reuse
9.
Function call is used
Message passing is used
10.
Function abstraction is used
Data abstraction is used
11.
Algorithm is given importance
Data is given importance
12.
Solution is solution-domain specific
Solution is problem-domain specific
13.
No encapsulation . Data and function are separate
Encapsulation packages . code & data altogether. Data & functionalities are put together a single entity
14.
Relational between programmer & program is emphasized
Relational between programmer user is emphasized
15.
Data driven technique is used
Is driven by delegation of responsibilities.
BASICS CONCEPTS OF OOP
OOP is a method of implementation in which programs are organized as co-operative collections of objects, each of which represents an instance of some class & whose classes are all members of a hierarchy of classes united through the property called inheritance.
Concepts of OOP:
Objects
Classes
Data abstraction
Data Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message Passing
Classes and objects :
Object is anything having crisply defined conceptual boundaries.
Eg: Book, pen, train, employee etc...
Not an example : Beauty, river, sky etc…
An object has
- States or properties
- Operations
- Identity
Properties :- Properties maintain the internal state of object
Operations:- Operations provide the appropriate functionality to the object
Identity:- Identity differentiates one object from the other.
Class is a collection of objects . (or) The class is a prototype or blueprint or model that defines different features. A feature may be a data or an operation. Data are represented by instance variables or data variables in a class. The operations are also known as methods or functions.
Object Model is defined by the means of classes and objects.
1. Object is an instance of class datatype
2. It gives life to a class
3. It is a container for storing its features
4. It occupies memory location
5. It can be manipulated Class Object
Class is a datatype
It generates object
It is the prototype or model
It doesn’t occupy memory location
IT can’t be manipulated because it is
not available in the memory
Mapping real world entity to object oriented programming:
Entity
Properties
Operations
Data
Functions
Real World Abstraction OOP Class
Different styles of representing an object:
Object Name
Attribute 1
:
:
:
Attribute N
Operation 1
:
:
Operation N
Oprn1
OprnN
Oprn2
Attr 1
:
AttrN
Object Name
Attribute 1
:
:
:
Attribute N
Operation1
Operation2
Operation3
Oprn – operation, Attr - Attribute
Encapulation :
Is a mechanism that associates the data and code that manipulates the data and keep them safe from external interference and misuse.
Data Abstraction :
Creating new data types using encapsulated items that are suited to an application to be programmed is called as data abstraction.
Abstract Data Types(ADT) :
The data types created by data abstraction are called as abstract data types.
Inheritance :
Is a process of deriving a new class from the existing class without modifying it.
Advantage :
· Adding new features to the system without modifying the existing one.
· Easy to enhance the system
· Reusability of code.
Differentiate data abstraction and encapsulation.
S.No
Data abstraction
Encapsulation.
1
Separates interface and implementation
Groups related items into one group
2
Provide access to a specific part of data
Hides the data and the user cannot access the same directly
3
Defined as a data type called class which separates interface from implementation
Packages data and functionality and hides the implementation details
Polymorphism :
Ability to take more than one form. Two types :
· Compile time polymorphism(Static or Early binding) –Linking done at compile time. Eg: Function overloading, Operator Overloading
· Runtime Polymorphism(Dynamic or Late binding) - Linking done at run time.
Eg : Virtual Function
Message Communication :
Objects can communicate(interact) with each other through functions. Message passing involves specifying the name of an object, name of the function(message) and information to be sent. It is similar to function call.
Example : student.marks(rollno);
Where student – object marks – message rollno - information
Benefits or advantages or Merits of OOP:
OOP offers several benefits to both the program designer and user.
· Extend the program without modifying the existing one using the concept of inheritance provides reusability of code.
· The standard library can be extended by users reduces the amount of code and allow us to build reliable programs.
· Data hiding allow us to build secure programs.
· Easily partitioned a large project into small module and handled easily.
· Object oriented systems can be easily upgraded from small to large systems.
· Software complexity can be easily managed.
· Suitable for solving complex problems.
· Easily map the real world problems.
· Software maintenance cost reduced.
· Software quality improved.
Applications of OOP :
The areas make use of OOP are real time systems, Digital Image Processing, Neural networks, Pattern Recognition, AI and expert systems, Mobile computing, Parallel Computing, DBMS, Data warehousing and Data Mining, Object oriented databases.
Structure of a C++ program :
Include Files
Class Declarations
Member Function Definitions
Main Function Program
The 4 sections may be placed in separate or same file.
• Organize the program into 3 separate files
1. Class Declarations
2. Member Function Declarations
3. The main function which includes previous 2 files.
Advantage :
• Abstracts the implementation details from other users.
• Resembles client-server model
•
Member Function
Class Definition
Server
Client
Main FunctionDifferent phases of C++ program execution.
· Creating a Program
· Compiling a Program
· Linking the program with functions that are needed from the C++ library
· Executing the program
FUNDAMENTALS OF C++
Introduction :
• Object Oriented Programming Language
• Developed by Bjarne Stroustrup at AT & T Bell Laboratories in the year
1980
• Extension of C
• C with OO concepts
• Called as C with Classes
Applications C++ :
• Able to handle very large programs
• Suitable for developing editors, compilers, databases, communication
systems and complex real world problems.
• Able to map real world problem properly.
• Programs are easily maintainable and expandable.
Character set :
• All Uppercase and Lowercase Alphabets A..Z & a..z
• All digits from 0..9
• Special characters
TOKENS :In a C++ program the smallest individual units are known as C++ Tokens
Eg : constants, identifiers, keywords, operators, etc.,
Identifiers :
• Every word in C++ program can be either Identifier or Keyword
• Identifier is a name given to Variables, Functions, Constants,
Symbolic constants
RULES FOR IDENTIFIERS :
• Consists of only letters,digits or underscore
• First character must be an alphabet
• Any length - Only first 31 characters are significant
• Cannot use a keyword
• Must not contain white space
Example :
Sum, avg, total, mark, a, b
Keywords :
• Built in words--- Fixed Meaning ( These meanings can’t be
changed.)
• Written in lowercase letters
Example:
void, case, if, int ,float ,else, while
Data Types :
C++ supports three classes of datatypes:-
· •
Primary (or fundamental ) or built-in datatypes
· •
Derived datatypes
· User-defined datatypes
Primary (or fundamental ) or built-in datatypes :
int, float, double, char, short int, long int, signed short int, unsigned
short int etc.,
Derived datatypes
• Array
• Function
• Pointer
User-defined datatypes
• Structure
• Union
• Class
• Enumeration
VARIABLES :
· Entity whose value can be changed during program execution.
· All variables must be declared before it can be used in the program.
Syntax:
datatype variable name;
Example :
int a,b,sum;
float x;
char c, s[10];
DYNAMIC INITIALIZATION OF VARIABLES:
It is also possible in C++ to declare a variable at the point of their first usage.
Example :
float avg = sum/n;
for(int i = 0 ; i < 10 ; i++)
OPERATORS
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operator
• Bitwise Operators
• Special Operators
Arithmetic Operators :
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulo Division
Example :
x + y, a - b, a * b, f / s, f % s
Relational Operators :
< : Less than
> : Greater than
<= : Less than or equal to
>= : Greater than or equal to
!= : Not equal to
Example :
x <> b, a <= b, f >= s, f != s
Logical Operators :
&& : Logical AND
|| : Logical OR
! : Logical NOT
Example :
a > b && x == 10;
a < b || a < n
!(x >= y)
Assignment Operators :
•Assignment Opeartor
•Compound Assignment Operators
Assignment Operator :
= : Assign value to a variable
Syntax :
variable = expression;
Example :
a = 100;
b = z + 10 *a;
COMPOUND ASSIGNMENT OPERATORS :
Syntax :
variable opeartor = expression/constant
x = x + 10 can be written as x + = 10;
operator : can be any arithmetic, relational, logical operator.
Compound Assignment Operators :
+=, -=, *=, /=, %=, &=, |=, <<=, >>=
Example :
A+=exp; a-=exp; a*=exp;
INCREMENT AND DECREMENT OPERATORS :
Increment Operator : ++
Pre Increment - Eg: ++a
Post Increment – Eg: a++
Example : int a=10, b=10;
a = ++b assigns b = 11, a=11
a= b++ assign a = 10, b=11
Decrement Operator : --
Pre Decrement - Eg: --a
Post Decrement – Eg: a--
CONDITIONAL OPERATOR
Ternary operator pair ?:
Syntax :
exp1 ? exp2 : exp3
True False
Example :
if (a>b)
x=a;
else x=b;
Can be written as
x=(a>b) ? a : b
BITWISE OPERATORS
Operator Meaning
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
<<
Shift Left
>>
Shift Right
~
One’s complement
SPECIAL OPERATORS :
• Comma operator
• Size of operator
• Pointer operators
• Member selection operator
COMMA OPERATOR :
• Used to link the related expressions together
• Used in for loops and while loops
Example 1: swapping two numbers
t = x, x = y, y = t;
Example 2 :
a = (x=10,y=5,x+y);
Takes value from left to right manner:
1.Assigns 10 to the variable x
2.Assigns 5 to y
3.And finally assigns 15 to the variable a
Sizeof operator :
• Is a compile time operator
• It returns the number of bytes that the operand occupies
• Operand may be a variable, a constant or a datatype
Syntax :
sizeof(data-type);
sizeof(variable);
Example :
M=sizeof(sum) returns 2 if sum is int
N=sizeof(long int) returns 4
a =sizeof(float) returns 4
a =sizeof(double) returns 8
a =sizeof(long double) returns 10
Additional Operators in C++ :
<< - Insertion operator
>> - Extraction operator
:: - Scope resolution operator
::* - Pointer-to-member declarator
->* - Pointer-to-member operator
.* - Pointer-to-member operator
new - Memory allocation operator
delete - Memory release operator
endl - Line feed operator
setw - Field width operator
Scope resolution operator ::
• Used to access the global variable.
Example :
#include
int a = 10;
main()
{
int a= 50;
a = a+100;
cout<cout<<::a;
}
Output :
150
10
EXPRESSIONS
• Combination of operands and operators
Example :
a*b-c
(m+n)*(x+y)
a*b/c
3*x*x+2*x+1
TYPE CONVERSION :
• Implicit or AutomaticType conversion
• Explicit Type Conversion
Implicit Type conversion :
Compiler performs type conversion of data items when an expression consists of data items of different data types.
Explicit Type Conversion :
Syntax:
(data-type) expression;
(data-type) variable-name;
or
data-type(expression);
data-type(variable-name);
Example:
int a,b;
float c;
c=a/b;
c=(float) a/b;
CONSTANTS:
• Fixed values that do not change during the execution of a program.
Types of constants:
•Numeric constants :
1) Integer Constants 2) Real Constants
•Character constants:
1) Single character 2) String constants
NUMERIC CONSTANTS :
INTEGER CONSTANTS: Sequence of digits.
Types of Integer Constants:
Decimal Integer constant: consists of a set of digits.(0 through 9 preceded by an optional + or - sign.
Eg : 1234 , -3215, 0, 65872, +77
• Embedded spaces, commas and non digit characters are not permitted between digits.
23,860 23 860 $555 - Not Permitted
Octal Integer Constant:
•Combination of digits (0 through 7 with a leading 0).
Eg : 088 , 0 , 0564, 0115
Hexadecimal Integer Constant:
•Sequence of digits (0 through 9, A through F with a leading 0x,0X)
Eg : 0X3, 0x3, 0XDEF, 0x8E
REAL CONSTANTS
•Numbers containing fractional parts
•These numbers are called real (or floating point) constants.
Eg : 0.0083 -0.78 475.75 +36.0
215. .95 -.71 +.5
Real number may be expressed in exponential (or scientific notation).
Syntax:
mantissa e exponent
•Mantissa- real number expressed in decimal notation (or) an integer.
CHARACTER CONSTANTS
Single character constant:
•contains a single character enclosed within a pair of single quote marks.
Eg : ‘5’ ‘X’ ‘;’ ‘ ‘
‘5’– not the same as 5
printf(“%d”,’a’);
o/p: 97(ASCII value of a =97)
STRING CONSTANTS:
• Sequence of characters enclosed in double quotes.
• Characters may be letters, numbers, special characters and blank space
Eg : “hai!” “1981” “WELLDONE” “X” “8+7”
“X” (does not have an equivalent integer value) not equal to ‘X’ (have an equivalent integer value)
Enumerated Data Types :
•User defined data type.
•Values ranges over a finite set of identifiers called as enumeration constants.
Syntax :
enum identifier {set of constants};
Example :
enum color {red, blue, green};
color a,b;
b = red; a = blue;
cout << a << b << c; displays 1 0
PREPROCESSOR :
It is a program that processes the source code before it passes through the compiler.
PREPROCESSOR DIRECTIVES:
It is placed in the source program before the main function.
3 CATEGORIES:
• Macro substitution directives
• File Inclusion directives
• Compiler Control directives
MACRO SUBSTITUTION DIRECTIVES
Identifier in the program is replaced by a predefined value(string). Also called as symbolic constant declaration.
Syntax:
#define identifier(sym. Const. name) value
Example for Simple Macro Substitution
#define PI 3.14
#define NAME “XXX”
#define SUM 2*3-1
Argumented Macro Substitution(Macro function) :
Syntax:
#define identifier(f1, f2,…,fn) string
Example :
#define CUBE(x) (x*x*x)
In program:--
The above example is expanded as
volume=CUBE(side); --- > (side*side*side)
UNDEFINING A MACRO:
#undef identifier
FILE INCLUSION DIRECTIVES
SYNTAX:
#include
Searched only in the standard directory.
Example :
#include
SYNTAX:
#include “filename”
Preprocessor inserts the entire contents of filename into the source code of the program. Search for the file is made first in the current directory and then in the standard directories.
Example :
#include “sum.cpp”
Operator Precedence and Associativity
:
Precedence of operator :
• Specifies which operator can be evaluated first.
• Each operator in C++ has a precedence associated with it.
Precedence of arithmetic operators :
High priority * / %
Lower priority + -
Example :
Evaluate x=a-b/3+c*2-1;
Evaluate y=a-b/(3+c)*(2-1);
Evaluate z=a-(b/(3+c)*2)-1;
ASSOCIATIVITY :
•Specifies the direction - (from left to right (or) right to left) in which the expression is evaluated, while using the particular operator.
•It is also differs from operator to operator.
CONTROL STATEMENTS
BRANCHING STATEMENTS
• If Statement
• If-Else Statement
• Switch Statement
• Goto Statement
• Break Statement
• Continue Statement
LOOPING STATEMENTS
• For Loop
• While Loop
• Do-while Statement
IF STATEMENT
: used to control the sequence of the execution of statements.
if(test-expression)
statement;
if(test-expression)
{
statement 1;
statement 2;
}
Example :
if (x == 100){ cout << "x is "; cout << x;}
IF-ELSE STATEMENT
: Some actions are performed even though the test expression fails.
if(test-expression) if(test-expression)
{ statement 1;
statement 1; else
statement 2; statement 2;
}
else
{
statement 3;
statement 4;
}
statement 5;
Example : if (x == 100) cout << "x is 100";else
cout << "x is not 100";
ELSE IF STATEMENTS :
used when there are multiple conditions and different actions to be taken under each condition. (Multi-way decision)
if(test-expression 1)
statement 1;
else if(test-expression 2)
statement 2;
else if(test-expression 3)
statement 3;
else
statement 4;
Example :
if (x > 0) cout << "x is positive";else if (x < 0) cout << "x is negative";else
cout << "x is 0";
FOR LOOP
: It is used to execute statement a fixed number of times.
for(initialization;condition;updation)
statement;
for(initialization;condition;updation)
{
statement 1;
statement2;
}
statement;
// countdown using a for loop#include
Output :10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
WHILE LOOP
: It is used when the number of iterations to be performed are not known in advance.
while(expression)
{
statement 1;
statement 2;
}
statement;
Example: // custom countdown using while #include
Output :Enter the starting number > 88, 7, 6, 5, 4, 3, 2, 1, FIRE!
DO-WHILE LOOP :
It executes the body of a loop atleast once.
Syntax : do
{
statement 1;
statement 2;
}while(condition);
statement;
Example : // number echoer #include
Output :
Enter number (0 to end): 12345You entered: 12345Enter number (0 to end): 160277You entered: 160277Enter number (0 to end): 0
You entered: 0
BREAK STATEMENT :
It terminates the execution of loop and the control is transferred to the statement immediately following the loop.
for(i=0;i<20;i++) while(expr)
{ {
…. …..
if(condition) if(condition)
break; break;
…. …..
} }
statement; statement;
Example :#include
SWITCH STATEMENT
: used to replace multiple if-else statement.
switch(test-variable)
{
case v1:
statements;
break;
case v2:
statements;
break;
…..
default :
statements;
break;
}
statement;
Example :
switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }
CONTINUE STATEMENT
:It skips the remainder of the current iteration and initiates the execution of the next iteration.
for(j=0;j<20;j++) while(expr)
{ {
….. …..
if(expr) if(expr)
continue; continue;
…. ….
} }
Example :
#include
ARRAYS
-Set of data items of the same datatype under a common name.
-They are popularly known as Subscripted Variable.
Array Definition(Single dimensional Array) :
Syntax: datatype array_name[array_size];
Example:
int age[5];
char name[20];
Accessing Array Elements:
•It can be accessed by using array index or subscript which ranges from 1 to n.
Syntax:
array_name[index];
Example:
int age[5];
cout<
Array Initialization – at Definition
Syntax:
datatype array_name[size]={list of values separated by comma};
Example:
int age[5]={10,1,50,20,11};
int age[]={10,1,50,20,11};
Array Initialization – Not in Definition
-using For loop ,while or do-while loop
Example 1 :
int age[5];
for(int i=1;i<=5;i++)
cin>>a[i];
Example 2 : // arrays as parameters #include
Output :5 10 152 4 6 8 10
Two Dimensional Arrays
Syntax:
array_name[row_index][column_index];
Example:
int a[3][3];
cout<
Initialization at Definition
Syntax
datatype array_name[row_size][col_size]={
{elements of first row},
{elements of second row},
……….,
{elements of Nth row}
};
STRINGS
It is represented as an array of characters and the end of the string is marked by the NULL (‘\0’) character.
String constants : Are enclosed by double quotes.
Eg. cout<<“Welcome to SIT”;
STRING DECLARATION :
Syntax
char array_name[size];
Example:
char name[30];
cin>>name;
String Initialization:
Syntax:
char array_name[size]=“string”;
Example:
char month[10] = “April”;
STRING MANIPULATIONS
#include
-strlen(string_variable);
-strcat(string_variable1,string_variable2);
-strcpy(string_variable1,string_variable2);
-strcmp(string_variable1,string_variable2);
-strlwr(string_variable);
-strupr(string_variable);
Examples:
char name[20]=“hello”;
cout<
char name[20]=“rama”;last[20]=“world”;
int i;
cout<
cout<
MANIPULATORS
Manipulators are operators used to format the output display. To include the file #include
Endl : Used to feed one line.
Example : int a = 123, m = 21, n = 3; cout << a << endl << m << endl << n;
Output :
123
21
3
Setw(): Used to set the field width and used to display the output in right alignment form.
Example : int a = 123, m = 21, n = 3;
cout << setw(5) << a << endl << setw(5) <
123
21
3
setbase() : Used to set the base.
Example : int value = 15; cout << setbase(10) << value << endl;
cout << setbase(8) << value << endl; cout << setbase(16) << value << endl;
Output :
15
17
f
setfill() : Used to fill the unused space created using setw() with specified character.
Example : int a = 123, m = 21, n = 3; cout << setfill(‘*’);
cout << setw(5) << a << endl << setw(5) <
**123
***21
****3
setprecision() : Used to control the no. of digits after decimal point.
Example : float a=12.3456; cout << a << endl;
cout << setprecision(2) << a << endl; cout << a;
Output :
12.3456
12.35
12.35
flush() : Used to empty the output buffer.
Syntax : cout.flush();
Reference variable :
· alias (alternative name) for a previously declared variable.
· After that the 2 names can Provides an be used to access that variable.
Syntax : data-type var.name;
data-type & ref-name = var.name;
Example :
float total = 100;
float & sum = total; à sum and total = 100
total = total + 50; à sum and total = 150
sum = 0; à sum and total = 0
Need :
· Reduces the complexity of using pointer variable.
· Do the same function but not access the address.
FUNCTIONS
Elements of Function :
1. Function Prototype
2. Function Parameters
3. Function Definition
4. Function Call
5. return statement
Function Prototypes:
•Additional feature added to C++
•It provides the following information to the complier.
1.The name of the function
2.The type of the value returned by the function
3.The no. and type of arguments passed to the function
•When the function call is encountered, the complier checks the function call with its prototype to ensure that correct arguments are used if not then the compiler informs the user about that.
Syntax :
ret. type fun.name(arg1, arg2,...argn);
Example :
Function Prototype :
float volume (int, float);
Function Definition :
float volume (int x, float y)
{ float a;
body of the function;
return a;
}
Function call :// function example#include
Output :
The result is 8
Parameter Passing
• call by Value
• call by Address
•
call by Reference
Pass by Value :
•Updation of an argument within the function not affect the main function
Example :
float volume (int, float); //Fn prototype
float volume (int x, float y) //Fn definition
{
float a;
a = x * y;
x= x + 10; y = y + 100;
cout<
}
void main
{ int m =1, n = 2;
L = volume(m,n); //Function call
cout <
•Passing address instead of value then the updation of an argument within the function affect the main function also.
Example :
float volume (int *, float *); //Fn prototype
float volume (int *x, float *y) //Fn definition
{ float a;
a = *x * *y;
*x= *x + 10; *y = *y + 100;
cout<<*x<<*y;
return a;
}
void main
{ int m =1, n = 2;
L = volume(&m,&n); //Function call
cout <
Pass by Reference :
Updation of an argument within the function affect the main function also because instead passing address only value can be passed but we create a reference to that variable in the function
Example 1: // passing parameters by reference #include
Disadv of function:
•When the program executes the function call instruction the CPU stores the address of the instruction following the function call, copies the arguments of the function call onto the stack and finally transfers control to the specified function.
•The CPU then executes the function and stores the returned value in the predefined memory address and returns control to the calling function.
•It is a overhead in the execution time of the program
•Sometimes the execution of program takes lesser time than the context switch time..
INLINE FUNCTIONS
• C++ provide a alternative in the form of Inline functions.
• Inline functions are those whose function body is inserted in place of the function call statement during the compilation process. There is no context switch overhead.
• Similar to macro of C.
Disadv of macro : They are not functions then usual error checking does not occur during compilation
•Inline function enjoy both the flexibility and power offered by normal functions and macro functions.
Syntax :
inline ret.type fun.name(arguments)
{
Body of the function
};
Example 1 :
#include
Inline void hello()
{
cout<<”hello”<
int main()
{
hello();
cin.get();
return 0;
}
Output : hello
Example 2:
//To multiply two numbers
#include
inline float mul(float x, float y)
{return(x*y);}
void main()
{
float a,b;
cout<<“Enter 2 numbers”;
cin>>a>>b;
cout<cout<< “100 * 15 =“<
Output :
Enter 2 numbers 5 3
5*3=15
100*15=1500
DEFAULT ARGUMENTS
•C++ allow us to call the function without specifying all the arguments defined in the function prototype.
•The compiler assigns a default value to the argument which does not have a matching argument in the function call.
•The default values are specified in the function prototype.
Example :// default values in functions#include
No comments:
Post a Comment