Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 104

Object Oriented

Programming with C++


MODULE 1
Syllabus
Decision statements, control loop structures, arrays, Functions, Introduction, Parts of a function,
Passing arguments, return by reference, returning more values, default arguments, const
arguments, inline functions, function overloading, recursion
STATEMENTS IN C++
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input.
 A C++ program is made up of a series of statements.
The statements in C++ are classified into 4 types.
1. Type Declaration statements
2. Arithmetic statements
3. Input output statements
4. Control statements
TYPE DECLARATION
STATEMENTS
We have to declare the variables used in a program before using it.
The type declaration statements are used to declare the type of variables used in the program.
The type declaration statement is written at the beginning of main( ) function.
The syntax of type declaration statement is
data type variable1,variable2;

Example
int a,sum,flag;
float area, circ;
Arithmetic Statements
The arithmetic statements are used to perform different arithmetical operations.
A C arithmetic statement consists of a variable name on the left hand side of = and variable names & constants on
the right hand side of =.
The variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, -, *,
and /.
The syntax of arithmetic statement is
variable=expression;
Where expression may a variable, a constant or a mathematical expression.
Example
a=b;
k=10;
c=a+b;
TYPES OF ARITHMETIC
STATEMENTS

A C arithmetic statement can be classified into three 3. Mixed mode arithmetic


types. statement - This is an arithmetic statement
1. Integer mode arithmetic statement – In case of in which some of the operands are integers
integer mode arithmetic statement all operands are and some of the operands are real.
either integer variables or integer constants. Ex.: float s, p, an, rate, avg ;
Example: int i,j,k,l; int a, b, c, num ;
i=i+1; s = p * n * rate / 100.0 ;
k = i * j + 14 +l - 7 ; avg = ( a + b + c + num ) / 4 ;

2. Real mode arithmetic statement - This is an It is important to understand how the


arithmetic statement in which all operands are either real execution of an arithmetic statement takes
constants or real variables. place. Firstly, the right hand side is
Example: float r,area,circ ; evaluated using constants and the
area = 3.14 * r*r; numerical values stored in the variable
circ = 2.0*3.14*r ; names. This value is then assigned to the
variable on the left-hand side.
INTEGER AND FLOAT
CONVERSIONS
 An arithmetic operation between an integer and
integer always generates an integer result. Operation Result Operation Result

 An operation between a real and real always 9/4 2 4/9 0


generates a real result. 9.0/4 2.25 4.0/9 0.44

9/4.0 2.25 4/9.0 0.44


 An operation between an integer and real always
produces a real result. In this operation the integer 9.0/4.0 2.25 4.0/9.0 0.44
is first promoted to a real and then the operation is
performed. Hence the result is real.
INPUT OUTPUT STATEMENTS
The C++ compiler also determines
The Standard Output Stream (cout) #include <iostream> the data type of variable to be
int main() output and selects the appropriate
The predefined object cout is an { stream insertion operator to display
instance of ostream class. char str[] = "Hello C++"; the value.
cout << "Value of str is : " <<
The cout object is said to be str << endl; The << operator is overloaded to
"connected to" the standard output } output data items of built-in types
device, which usually is the display When the above code is integer, float, double, strings and
screen. compiled and executed, it pointer values.
produces the following result −
The cout is used in conjunction with The insertion operator << may be
the stream insertion operator, Value of str is : Hello C++ used more than once in a single
which is written as << which are statement as shown above and endl
two less than signs as shown in the is used to add a new-line at the end
following example. of the line.
INPUT OUTPUT
STATEMENTS The C++ compiler also determines the
data type of the entered value and
selects the appropriate stream
#include <iostream> extraction operator to extract the
The Standard Input Stream (cin) void main() value and store it in the given
{ variables.
The predefined object cin is an char name[50];
instance of istream class. The stream extraction operator >>
cout << "Please enter your name: "; may be used more than once in a
The cin object is said to be attached to cin >> name; single statement.
the standard input device, which cout << "Your name is: " << name <<
usually is the keyboard. endl; To request more than one datum you
can use the following −
The cin is used in conjunction with the }
stream extraction operator, which is When the above code is compiled and cin >> name >> age;
written as >> which are two greater executed, it will prompt you to enter a
than signs as shown in the following name. You enter a value and then hit This will be equivalent to the
example. enter to see the following result − following two statements −

Please enter your name: cplusplus cin >> name;


Your name is: cplusplus cin >> age;
CONTROL STATEMENTS
 Traditionally program flow is sequential.

 The control statements are certain kinds of statements that are able to alter program flow.

 In general, every control statements will take a decision first.

 Based on the decision (i.e. true or false) it has taken, control will branch to somewhere else or it will
execute some statements repeatedly.

 Hence, the control statements are broadly classified into categories. They are

 Decision Making and Branching


 Decision Making and Looping
DECISION MAKING AND
BRANCHING STATEMENTS
These types of control statements will take a decision first.
Based on the decision it has taken, the program control will branch to other parts of the
program. That is it will alter program flow to somewhere else.
The statements belonging to this category are
Simple if statement
if else statement
Nested if else statement
The else if ladder
switch case statement
The Simple if Statement
The syntax of simple if statement is
#include<stdio.h>
if(Condition) void main()
{ {
Statement Block; int a=10,b=12,small;
} if(a<b)
Next Statement; {
small=a;
Here, the ‘Condition’ will be evaluated first. If the value }
of the condition is TRUE then ‘Statement Block’ will be cout<<“Smallest number is
executed. ”<<small;
After that ‘Next Statement’ will be executed. }
If the ‘Condition’ is FALSE, ‘Statement Block’ will be
skipped and the ‘Next Statement’ will be executed.
The Simple if Statement- Flow chart
The if else Statement
Syntax /* Program to find smallest among 2 numbers */
if(Condition) #include<iostream.h>
{ void main()
True block statements; {
} int a=10,b=12,small;
else if(a<b)
{ {
False block statements; small=a;
} }
Next Statement; else
{
Here, the ‘Condition’ will be evaluated first. If the small=b;
value of the ‘Condition’ is TRUE, then ‘True block }
statements’ will be executed. If the value of the cout<<“Smallest number is ”<<small;
‘Condition’ is FALSE, then ‘False block statements’ will }
be executed.
The if else Statement- Flow chart
Nested if else statement
When an if else statement is present inside another if else statement, then it is known as
nested if else statement.
There is no limit on how deeply the if’s and the else’s can be nested.
This statement has different syntaxes because an if else may present in the if part of an if else
statement or else part of an if else statement or an if else statement may present in if part as
well as else part.
One General Syntax of Nested If Here ‘condition1’ will be
evaluated first. If it is TRUE
if(condition1) else then ‘condition2’ will be
{ { evaluated. If it is also TRUE,
if(condition2) if(condition3) then ‘Statement block1’ will be
{ { executed. If ‘condition1’ is
Statement block1; Statement block3; TRUE and ‘condition2’ is FALSE,
} } then ‘Statement block2’ will be
else else executed. If ‘condition1’ is
{ { ‘FALSE’ then ‘condition3’ will
Statement block2; Statement block4; be evaluated. If it is TRUE then
} } ‘Statement block3’ will be
} } executed. If ‘condition1’ is
FALSE and ‘condition3’ is
FALSE, then ‘Statement block4’
will be executed.
/* Program to find largest among three numbers
using nested if */
#include<iostream.h>
void main() else
{ {
int a,b,c; if(b>c)
cout<<“Enter 3 numbers”<<endl; {
cin>>a>>b>>c; Large=b;
if(a>b) }
{ else
if(a>c) {
{ Large=c;
Large=a; }
} }
else cout<<“Largest number is ”<<large;
{ }
Large=c;
}
}
Nested if Statement- Flow chart
The else if ladder
 The else if ladder statement is used to test a
else if(condition-3)  First of all, condition-1 is tested
set of conditions in sequence.
 An if condition is tested only when all previous { and if it is TRUE then
Statement block3; ‘Statement block1’ will be
if conditions in else if ladder is false.
 If any of the conditional expression evaluates } executed and control comes
else if(condition-4) out of whole else if ladder.
to true, then it will execute the corresponding
{  If condition-1 is FALSE then
code block and exits whole if-else ladder.
Statement block4; only condition-2 is tested.
}  Control will keep on flowing
Syntax
. downward, if none of the
if(condition-1)
. conditional expression is true.
{
.  The last else is the default
Statement block1;
else block of code which will get
}
{ executed if none of the
else if(condition-2)
Statement conditional expression is true.
{
blockN;  Default else block is optional in
Statement block2;
} else if ladder statement.
}
Else if Ladder- Flow chart
else if ladder – Example Program
/* Program using else if ladder statement to print else if (marks >= 70 && marks < 90)
Grade of a Student */ {
#include<iostream.h> /* Marks between 70-89 */
#include<conio.h> cout<<"YOUR GRADE :
void main() B“<<endl;
{ }
int marks; else if (marks >= 50 && marks < 70)
cout<<"Enter your marks between 0-100“<<endl; {
cin>>marks; /* Marks between 50-69 */
if(marks >= 90) cout<<"YOUR GRADE :
{ C“<<endl;
/* Marks between 90-100 */ }
cout<<"YOUR GRADE : A“<<endl; else
} {
/* Marks less than 50 */
cout<<"YOUR GRADE :
Failed";
The switch Statement
 The switch statement is a multi-way decision making statement and is used to select a choice from a
list of alternatives.
 When we want to solve multiple option type problems, for example: Menu like program, where one
value is associated with each option and we need to choose only one at a time, then, switch
statement is used.
 Switch statement is a control statement that allows us to choose only one choice among the many
given choices.
 The expression in switch evaluates to return an integral value, which is then compared to the values
present in different cases.
 It executes that block of code which matches the case value. If there is no match, then default block is
executed (if present).
The switch Statement
The general form of switch
 Here, switch, case and break are
statement is,
keywords.
 The constants followed by case
switch(expression) case value-4:
keywords should be either integer
{ block-4;
constants or character constants.
case value-1 : break;
 The expression can be integer
block-1; .
expression or a character expression.
break; .
 Value-1, value-2 etc. are case labels
case value-2: .
which are used to identify each case
block-2; default:
individually. Case labels always end with
break; default-
a colon ( : ). Each of these cases is
case value-3: block;
associated with a block.
block-3; }
 A block is nothing but multiple
break; Statement-x;
statements which are grouped for a
particular case.
The switch Statement
 Whenever the switch is executed, the value of
test-expression is compared with all the cases  The break statement is optional. If omitted,
which we have defined inside the switch. execution will continue on into the next case.
 Suppose the test expression contains value 4.  The flow of control will fall through to
 This value is compared with all the cases until subsequent cases until a break is reached.
case whose label 4 is found in the program.  The default case is an optional one.
 As soon as a case is found, the block of  Whenever the value of test-expression is not
statements associated with that particular case matched with any of the cases inside the
is executed and control goes out of the switch. switch, then the default will be executed.
 The break statement is used inside the switch  Otherwise, it is not necessary to write default
to terminate a statement sequence. in the switch.
 When a break statement is reached, the switch  Once the switch is executed the control will
terminates, and the flow of control jumps to go to the statement-x, and the execution of a
the next line following the switch statement. program will continue.
The switch Statement- Example
Program
/* Example program to demonstrate the switch(choice) default:
working of switch statement */ { cout<<"you have passed
#include<stdio.h> case 1: a wrong key");
void main( ) cout<<"Enter 2 cout<<"\n press any key
{ numbers“<<endl; to continue");
int a, b, c, choice; cin>>a>>b; }
while(choice != 3) c = a + b; }
{ cout<<c; getch();
/* Printing the available break; }
options */ case 2:
cout<<endl<<"1. Press 1 for cout<<"Enter 2
addition"); numbers“<<endl;
cout<<endl<<"2. Press 2 for cin>>a>>b;
subtraction"); c = a - b;
cout<<"\n Enter your cout<<c;
choice"; break;
/* Taking users input */
cin>>choice;
Flow chart-
Switch Statement
DECISION MAKING AND
LOOPING STATEMENTS
Looping is the process of executing a set of statements repeatedly until a specified condition is
met.
Depending upon the position of a test condition in a program, loops are classified into two
types. They are
◦ Entry Controlled loops: In this type of loops the test condition is tested before entering the loop body.
for Loop and while Loop are entry controlled loops.
◦ Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of loop
body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is
true or false. do – while loop is an exit controlled loop.
The for loop
The initialization statement is executed only
The for loop is used to execute a set of statements once.
repeatedly until a particular condition is satisfied. Then, the test condition is evaluated. If the test
condition is evaluated to false, the for loop will
The syntax of for loop is be terminated.
However, if the test condition is evaluated to
for(Initialization; Test Condition; Increment/Decrement) true, statements inside the body of for loop are
{ executed, and the Increment/Decrement
Statement block; (Updation) part will be executed.
} Again the test expression is evaluated. This
process goes on until the test expression is false.
When the test expression is false, the loop
terminates.
In the program,

i is initialized to 1.

The test expression i < 11 is evaluated. Since 1 less than


11 is true, the body of for loop is executed.
Example 1
This will print the 1 (value of i) on the screen.
/* Print numbers from 1 to 10 */
#include <iostream.h>
The update statement ++i is executed. Now, the value of i
void main()
will be 2.
{
int i;
Again, the test expression is evaluated to true, and the
for (i = 1; i < 11; ++i)
body of for loop is executed. This will print 2 (value of i)
{
on the screen.
cout<<i;
}
Again, the update statement ++i is executed and the test
}
expression i < 11 is evaluated. This process goes on until i
becomes 11.
Output
When i becomes 11, i < 11 will be false, and the for loop
terminates.
1 2 3 4 5 6 7 8 9 10
Flow chart –for loop
The while loop
While loop is an entry control loop. The Syntax of while loop is #include<iostream.h>
void main()
{
while(condition)
int i=1;
{ while (i<=5)
Statements; {
}
cout<<i;
i++;
At first, the condition will be evaluated. }
If the value of the condition is TRUE then statements in the loop }
will be executed.
After that again condition will be evaluated. Output
If it is TRUE then the statements in the loop will execute once
more. 12345
That is, statements in the loop will execute repeatedly until the
condition becomes FALSE.
Flow chart- while loop
The do..while loop
The do..while loop is an exit control loop.
The Syntax of do..while loop is
do
{
Statements;
} while(condition);
At first, the statements in the loop will execute once.
After that the condition will be evaluated. If the value of the condition is TRUE then statements in the
loop will be executed once more.
Statements in the loop will execute as many times until the condition becomes FALSE.
The difference between while loop and do..while loop is that the do..while loop will execute at least once
even when the condition is initially false.
Example & Flow chart of do..while loop
Example

#include<iostream.h>
void main()
{
int i=1;
do
{
cout<<i;
i++;
}while(i<=5);
}
Output
12345
Various forms of for loop in C
1. Initialization part can be skipped from loop as shown for (num=10; num<20; )
below, the counter variable is declared before the loop. {
/*Statements */
int num=10; num++;
for (;num<20;num++) }

Note: Even though we can skip initialization part but 3. The counter variable is initialized before the
semicolon (;) before condition is must, without which loop and incremented inside the loop. This is also
we will get compilation error. possible.

2. Like initialization, you can also skip the increment part int num=10;
as we did below. In this case semicolon (;) is must after for (;num<20;)
condition logic. In this case the increment or decrement {
part is done inside the loop. /*Statements*/
num++;
}
4. We can use 2 or more loop control variables.

#include<stdio.h>
void main() 5. The infinite loop
{
int i,j; for(;;) statement;

for(i=0, j=10; i<10; i++, j--) The code below will print hello world for infinite number
{ of times
cout<<i<<" +" <<j<<"=
“<<i+j<<endl; for( ; ; )
} printf("Hello World\n");
cout<<"The value of i is “<<i;
} There is no need of any expression for an infinite for
In the example above, i and j both are loop.
initialized, separated by a comma operator. In
the increment expression, i is incremented and
j is decremented.
6. Comma operator in for loop
Example
The comma operator (,)is primarily used in
conjunction with the ‘for’ statement. This #include<stdio.h>
operator permits two different expressions to void main()
appear within the for loop syntax. {
int x=0,j,k;
Syntax: cout<<“\n The values of K,J and X
are \n”;
for(initial condition1,initial condition2;Test for(k=0,j=5;k<5;k=k+2,j--)
condition;updation1, updation2) {
{ x++;
Statements; cout<<k<<"\n\t"<<j<<"\t“<<
} x<<endl;
}
We can have any number of initial conditions }
separated by comma operator and any number
of updation parts separated by comma operator
but only one test condition is allowed.
The break and continue Statements
With the help of break and continue statements, we can jump out of loop anytime and able continue
looping by skipping some part of the code.

The break statement in C

 In any loop break is used to jump out of loop skipping the code below it without caring about the
test condition.
 It interrupts the flow of the program by breaking the loop and continues the execution of code
which is outside the loop.
 The common use of break statement is in switch case where it is used to skip remaining part of the
code.
How does break statement works?
/* Program to calculate the sum of a maximum of 10 numbers If
a negative number is entered, the loop terminates */

# include <iostream.h>
int main()
{
int i;
double number, sum = 0.0; cout<<"Sum = “<<sum;
for(i=1; i <= 10; ++i) return 0;
{ }
cout<<"Enter a number “<<i;
cin>>number; Output
Enter a number1: 2.4
/* If the user enters a negative number, the loop ends */ Enter a number2: 4.5
if(number < 0.0) Enter a number3: 3.4
{ Enter a number4: -3
break;
} Sum = 10.30
sum += number; // sum = sum + number;
}
The continue statement in C
Like a break statement, continue statement is also used with if condition inside the loop to
alter the flow of control.
When used in while, for or do...while loop, it skips the remaining statements in the body of
that loop and performs the next iteration of the loop.
Unlike break statement, continue statement when encountered doesn’t terminate the loop,
rather interrupts a particular iteration.
How continue statement works?
/* Program to calculate the sum of a maximum of
10 numbers. Negative numbers are skipped from
the calculation */ cout<"Sum = “<<sum;

# include <stdio.h> return 0;


int main() }
{
int i; Output
double number, sum = 0.0; Enter a n1: 1.1
for(i=1; i <= 10; ++i) Enter a n2: 2.2
{ Enter a n3: 5.5
cout<<endl<<"Enter a n: “<<i; Enter a n4: 4.4
cin>>number; Enter a n5: -3.4
Enter a n6: -45.5
if(number < 0.0) Enter a n7: 34.5
{ Enter a n8: -4.2
continue; Enter a n9: -1000
} Enter a n10: 12
sum += number; Sum = 59.70
}
Nested for loops

 C programming language supports nesting of one


loop inside another.
Syntax
 You can define any number of loop inside
another loop. for(initialization; condition; update)
{
 You can also have any number of nesting level. /* statements */
You can put any type of loop in another type.
for(initialization; condition;
 For example, you can write a for loop inside update)
while loop, while inside another while etc. {
/* Inner loop statements
 Using a for loop within another for loop is said to */
be nested for loop. }

 In addition we can have any number of loop /* statements */


nested inside other. }
Example
To understand the above program easily let us first
/* C program to print multiplication table from 1 to 5 */ focus on inner loop.
#include <stdio.h>
void main()  First the initialization part executes initializing j=1.
{ After initialization it transfer program control to
/* Loop counter variable declaration */ loop condition part i.e. j<=5.
int i, j;
 The loop condition checks if j<=5 then transfer
/* Outer loop */ program control to body of loop otherwise
for(i=1; i<=10; i++) terminated the inner loop.
{
/* Inner loop */  Body of loop contains single printf("%d\t", (i*j));
for(j=1; j<=5; j++) statement. For each iteration it print the product
{ of i and j.
cout<<"\t“<<(i*j);
}  Next after loop body, the loop update part
receives program control. It increment the value
/* Print a new line */ of j with 1 and transfer program control back to
cout<<endl; loop condition.
}
}
Body of loop does not contain any statement rather it
From the above description it is clear that the inner
contain another loop i.e. the inner loop we discussed
loop executes 5 times.
above.
For i=1 it prints the product of i and j
The program control is transferred to loop update
part i.e. i++ after inner loop terminates. The loop
1 2 3 4 5
update part increment the value of i with 1 and
transfer the control to loop condition.
Similarly for i=2 it prints
From the above description of outer loop, it is clear
2 4 6 8 10
that outer loop executes 10 times. For each time
outer loop repeats, inner loop is executed with
Next let us now concentrate on outer loop.
different value of i printing the below output.
In the outer loop first variable i is initialized with 1.
1 2 3 4 5
Then it transfer program control to loop condition
2 4 6 8 10
i.e. i<=10.
3 6 9 12 15
4 8 12 16 20
The loop condition part checks if i<=10 then transfer
5 10 15 20 25
program control to body of loop otherwise
6 12 18 24 30
terminate from loop.
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50
Arrays
An array is a collective name given to a group of similar elements stored in consecutive memory
locations.
These similar elements could be all integers or all floats or all characters etc.
For example, these similar quantities could be percentage marks of 100 students, number of chairs in
home, or salaries of 300 employees or ages of 25 students.
Thus an array is a collection of similar elements.
 Usually, the array of characters is called a “string”, where as an array of integers or floats is called
simply an array.
All elements of any given array must be of the same type i.e. we can’t have an array of 10 numbers, of
which 5 are int and 5 are float.
An array is also known as a subscripted variable. Before using an array its type and dimension must be
declared.
ARRAY DECLARATION
Example
Like other variables, an array needs to be declared so that the
compiler will know what kind of array and how large the array
int marks[30] ;
we want.
Here, int specifies the type of the variable, just as it
The syntax of declaring an array is
does with ordinary variables and the word marks
specifies the name of the variable.
data type arrayName [ SIZE ];
The number 30 tells how many elements of the type int
will be in our array.
where,
This number is often called the "dimension" of the
data type is a valid C data type that must be common to
array.
all array elements.
The bracket ( [ ] ) tells the compiler that we are dealing
arrayName is name given to array and must be a valid C
with an array.
identifier.
It's important to note that the size and type of an array
SIZE is a constant value that defines array maximum
cannot be changed once it is declared.
capacity.
ARRAY INITIALIZATION
Let us now see how to initialize an array while declaring it. The Following are a few examples that demonstrate this.
syntax of array initialization is as follows
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
datatype array_name[size] = { val1, val2, val3, ..... valN }; int n[] = { 2, 4, 12, 5, 45, 5 } ;
float press[] = { 12.3, 34.2 -23.4, -11.3 } ;
where,
While initializing an array mentioning the size of the
 datatype is the type of elements of an array. array is optional.
 array_name is the name of the array, which must be any valid
identifier.
 size is the size of the array.

val1, val2 … are the constants known as initializers. Each value is


separated by a comma(,) and then there is a semi-colon (;) after the
closing curly brace (}).
ARRAY INITIALIZATION
If the number of initializers is less than the specified
size then the remaining elements of the array are
assigned a value of 0.
If the number of initializers is greater than the size of
float temp[5] = {13.1, 4.3}; the array then, the compiler will report an error. For
example:
here the size of temp array is 5 but there are only
two initializers. After this initialization the elements int num[5] = {1, 2, 3, 4, 5, 6, 7, 8} /* error */
of the array are as follows:

temp[0] is 13.1
temp[1] is 4.3
temp[2] is 0
temp[3] is 0
temp[4] is 0
ACCESSING ELEMENTS OF AN
ARRAY
Once an array is declared, let us see how individual elements in the array can be referred.

This is done with subscript, the number in the brackets following the array name.

This number specifies the element’s position in the array.

All the array elements are numbered, starting with 0.

Thus, marks [2] is not the second element of the array, but the third.

int valueOfThirdElement = marks[2];


Entering Data into an Array
Here is the section of code that places data into an array:

for(i = 0;i <= 29;i++)


{
cout<<"\nEnter marks "; This process will be repeated until i becomes 29.
cin>>marks[i];
} This is last time through the loop, which is a good thing
because there is no array element like marks[30].
The for loop causes the process of asking for and receiving a
student’s marks from the user to be repeated 30 times.

The first time through the loop, i has a value 0, so the cin
statement will cause the value typed to be stored in the array
element marks[0], the first element of the array.
Reading Data from an Array
The balance of the program reads the data back out of the array and uses it to calculate the average.
The for loop is much the same, but now the body of the loop causes each student’s marks to be added
to a running total stored in a variable called sum.
When all the marks have been added up, the result is divided by 30, the number of students, to get the
average.

for ( i = 0 ; i <= 29 ; i++ )


{
sum = sum + marks[i] ;
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
ADVANTAGES OF USING AN
ARRAY
Similar data types can be grouped together under one name. for example, int a=1; int b=2; int
c=3; int d=4; int e=5; could be represented as- int X[5]={1,2,3,4,5};
It allows random accessing of elements using indices which saves a huge time.
It allocates memory in contiguous memory locations for its elements.
It does not allocate any extra space/ memory for its elements. Hence there is no memory
overflow or shortage of memory in arrays.
Iterating the arrays using their index is faster compared to any other methods like linked list
etc.
It can be used to implement other data structures like- stack,queues etc.
We can represent 2-D matrices using array.
DISADVANTAGES OF USING AN
ARRAY
 It is mandatory to determine the size of the array to store the elements in it.
As array elements are stored at consecutive memory locations, so insertion and deletion of an element
are difficult/time-consuming.
There is a certain chance of memory wastage/shortage.
It allows us to enter only fixed number of elements into it.
 We cannot alter the size of the array once array is declared.
Hence if we need to insert more number of records than declared then it is not possible.
We should know array size at the compile time itself.
Inserting and deleting the records from the array would be costly since we add or delete the elements
from the array, we need to manage memory space too.
It does not verify the indexes while compiling the array. In case there is any indexes pointed which is
more than the dimension specified, then we will get run time errors rather than identifying them at
compile time.
BOUNDS CHECKING
Unfortunately in C++ there is no way for the programmer to
determine the size of an array at runtime and so it becomes C++ doesn’t have bounds checking for arrays;
necessary for the programmer to keep track of the length of the it’s entirely up to the user to ensure they are
array. within the bounds of an array.

In C there is no check to see if the subscript used for an array Usually a symptom of out of bounds access is
exceeds the size of the array. some kind of undefined runtime error.

Data entered with a subscript exceeding the array size will simply For instance, your program may be crashing
be placed in memory outside the array; probably on top of other but not display an error message.
data, or on the program itself.

This will lead to unpredictable results, to say the least, and there
will be no error message to warn you that you are going beyond
the array size.

In some cases the computer may just hang.


TWO-DIMENSIONAL ARRAYS
The simplest form of multidimensional array is the two-dimensional array.
2D arrays in C language are generally defined as an array of arrays.
The 2D array can be represented as the collection of rows and columns as they are organized as
matrices.
The syntax of declaring a 2D array is
data_type array_name[rows][columns];

Where data_type can be any C data type (int, char, long, long long, double, etc.) and
array_name will be a valid C identifier, or variable.
Multidimensional arrays may be used by specifying
bracketed[] values for each row.
A two-dimensional array a, which contains three rows
and four columns can be shown and thought about like Below is an array with 3 rows and each row has 4
this – columns.

To make it easier, you can forget the 3 and keep it


blank, it'll still work.

int a[3][4] = {
{0, 1, 2, 3} , /*
initializers for row indexed by 0 */
{4, 5, 6, 7} , /*
In this sense, every element in the array a is identified by an initializers for row indexed by 1 */
element name in the form a[i][j], where 'a' is the name of {8, 9, 10, 11} /*
the array, and 'i' and 'j' are the indexes that uniquely initializers for row indexed by 2 */
identify, or show, each element in 'a'. };

The total number of elements in this array would be 12 The inside braces, which indicates the wanted row, are
elements(3 x 4 =12). optional.
The following initialization is the same to the previous
example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
ACCESSING TWO-DIMENSIONAL ARRAY ELEMENTS
The array that we have in the example below is
An element in a two-dimensional array is having the dimensions 5 and 4.
accessed by using the subscripts, i.e., row index
and column index of the array. These dimensions are known as subscripts. So this
array has first subscript value as 5 and second
For example − subscript value as 4.

int val = a[2][3]; So the array abc[5][4] can have 5*4 = 20 elements.

The above statement will take the 4th element To store the elements entered by user we are using
from the 3rd row of the array. two for loops, one of them is a nested loop.

How to store user input data into 2D The outer loop runs from 0 to the (first subscript -
array? 1) and the inner for loops runs from 0 to the
(second subscript -1).
We can calculate how many elements a two
dimensional array can have by using this This way the the order in which user enters the
formula: elements would be abc[0][0], abc[0][1], abc[0][2]…
so on.
The array arr[n1][n2] can have n1*n2 elements.
#include<stdio.h>
int main()
{

/* 2D array declaration*/
int abc[5][4];

/*Counter variables for the loop*/


int i, j;

for(i=0; i<5; i++)


{
for(j=0;j<4;j++)
{
cout<<endl<<"Enter value for abc[“<<i<<"]
[“<<j<<"]:";
cin>>abc[i][j];
}
}

return 0;
}
However the actual representation of this array in memory would be something like this:
#include<iostream.h>
float findAverage(int marks[]);
int main()

ARRAYS AND FUNCTIONS {


float avg;
int marks[] = {99, 90, 96, 93, 95};
Whenever we need to pass a list of avg = findAverage(marks); /* name of the
elements as argument to any function in C array is passed as argument. */
language, it is preferred to do so using an cout<<"Average marks = “<<avg;
array. return 0;
}
Passing a complete One-dimensional array
float findAverage(int marks[])
to a function
{
To understand how this is done, let's write a int i, sum = 0;
function to find out average of all the float avg;
elements of the array and print it. for (i = 0; i <= 4; i++)
{
We will only send in the name of the array sum += marks[i];
as argument, which is nothing but the }
address of the starting element of the array, avg = (sum / 5);
or we can say the starting memory address. return avg;
}
Output
94.6
Passing a Multi-dimensional array to a function void displayArray(int arr[3][3])
Here again, we will only pass the name of the array as {
argument. int i, j;
cout<<"The complete array is: \n";
#include<stdio.h> for (i = 0; i < 3; ++i)
void displayArray(int arr[3][3]); {
int main() /* getting cursor to new line */
{ cout<<endl;
int arr[3][3], i, j; for (j = 0; j < 3; ++j)
cout<<"Please enter 9 numbers for the {
array: \n"; /* \t is used to provide tab
for (i = 0; i < 3; ++i) space */
{ cout<<"\t“<<arr[i][j]);
for (j = 0; j < 3; ++j) }
{ }
cin>>arr[i][j]); }
} Output
} Please enter 9 numbers for the array:
/* passing the array as argument */ 1 2 3 4 5 6
displayArray(arr); 7 8 9
return 0;
} The complete array is:
1 2 3
4 5 6
Functions
 Function is a sub program which is used to  C language provides an approach in
execute frequently occurring operations. which we can declare and define a group
of statements once in the form of a
 When an operation is repeating several places in function and it can be called and used
a program, we can write that operation as a sub whenever required.
program and call that sub program wherever
necessary.  These functions defined by the user are
also known as User-defined Functions
 This helps in reducing the program size.
 C functions can be classified into two
categories,
1. Library functions/Built-in functions
2. User-defined functions
Functions
 Library functions are those functions
which are already defined in C library,
example printf(), scanf(), strcat() etc.
We just need to include appropriate
header files to use these functions.
These are already declared and defined
in C libraries.

 User-defined functions on the other


hand, are those functions which are
defined by the user at the time of
writing program. These functions are
made for code reusability and for
saving time and space.
Benefits of Using Functions
1. It provides modularity to your program's structure.
2. It makes our code reusable. We just have to call the function by its name to use it, wherever
required.
3. In case of large programs with thousands of code lines, debugging and editing becomes
easier if we use functions.
4. It makes the program more readable and easy to understand.
The components of a function
Function Declaration
1. Function Declaration or
Prototype declaration General syntax for function declaration is,

2. Function Definition returntype functionName(type1 parameter1, type2


parameter2,...);
3. Function Call
Like any variable or an array, a function must also be declared
before it is used. Function declaration informs the compiler about
the function name, parameters it accept, and its return type. The
actual body of the function can be defined separately. It's also
called as Function Prototyping.
Function Declaration
Function declaration consists of 4 parts. functionName
1. returntype
2. function name Function name is an identifier and it specifies the
3. parameter list name of the function. The function name is any
4. terminating semicolon valid C identifier and therefore must follow the
same naming rules like other variables in C
returntype language.

When a function is declared to perform some sort of parameter list


calculation or any operation and is expected to provide
with some result at the end, in such cases, a return The parameter list declares the type and number
statement is added at the end of function body. Return of arguments that the function expects when it is
type specifies the type of value (int, float, char, double) called. Also, the parameters in the parameter list
that function is expected to return to the program receives the argument values when the function is
which called the function. called. They are often referred as formal
parameters.
Note: In case your function doesn't return any value,
the return type would be void.
Function
Definition
The general syntax of function definition is, Function body

returntype functionName(type1 parameter1, type2 The function body contains the declarations and
parameter2,...) the statements(algorithm) necessary for
{ performing the required task. The body is enclosed
// function body goes here within curly braces { ... } and consists of three
} parts.

The first line returntype functionName(type1 1. local variable declaration(if required).


parameter1, type2 parameter2,...) is known as 2. function statements to perform the task inside
function header and the statement(s) within curly the function.
braces is called function body. 3. a return statement to return the result
evaluated by the function(if return type is void,
Note: While defining a function, there is no then no return statement is required).
semicolon(;) after the parenthesis in the function
header, unlike while declaring the function or
calling the function.
Calling a function
When a function is called, control of the program gets transferred to the function.
The syntax of function call statement is
functionName(argument1, argument2,...);
Example
Let's write a simple program with a main() function, and a user
defined function to multiply two numbers, which will be called
from the main() function. int multiply(int a, int b)
#include<stdio.h> {
int multiply(int , int); /* function declaration */ return (a*b);
void main() /* function definition, this can be done in one line
{ */
int i, j, result; }
cout<<"Please enter 2 numbers you want to multiply.“<<endl;
cin>>i>>j;
result = multiply(i, j); /* function call */
cout<<"The result of muliplication is: “<<result;
return 0;
}
Passing Arguments to a function
 Arguments are the values specified during the
function call, for which the formal parameters are
declared while defining the function.

 The arguments present in the function call statement


are known as actual parameters and the
corresponding arguments present in the function
definition are known as formal parameters.

 Actual parameters must correspond with formal


parameters in their number and the order of data
types.

In the above example program i and j are examples of


actual parameters and a and b are examples of formal
parameters.
 While declaring the function, we have declared
two parameters a and b of type int.

 Therefore, while calling that function, we need to


pass two arguments, else we will get compilation
error.

 The two arguments passed should be received in


the function definition, which means that the
function header in the function definition should
have the two parameters to hold the argument
values.

 These received arguments are also known as


formal parameters.

 The name of the variables while declaring, calling


and defining a function can be different.
Returning a value from function
 A function may or may not return a result.
But if it does, we must use the return statement to output the result.
return statement also ends the function execution, hence it must be the last statement of any
function.
If you write any statement after the return statement, it won't be executed.
The data type of the value returned using the return
statement should be same as the return type
mentioned at function declaration and definition.

If any of it mismatches, you will get compilation error.

The process of transferring control from one function


to another (until the other function returns) is known
as calling a function, or making a function call.

The function being called is known as the called


function, or more concisely, the callee.

The function that makes the call is known as the calling


function, or more concisely, the caller.

In the above example program main() is the calling


function and multiply() is the called function.
CLASSIFICATION OF USER
DEFINED FUNCTIONS
Based on the communication between calling function and called function, user defined
functions are classified into four types. They are
1. Function with arguments and return value
2. Function with arguments and no return value
3. Function with no arguments and return value
4. Function with no arguments and no return value
Function with arguments and return
value
This method allows us to pass the arguments to the function while calling the function.
This type of functions will return some value when we call the function from main () or any sub
function.
 Data Type of the return value will depend upon the return type of function declaration.
For instance, if the return type is int then return value will be int.
Function with arguments and return value means both the calling function and called function
will receive data from each other.
It’s like a dual communication.
Example
#include<stdio.h>
int large(int x, int y) /* function definition
int large(int a, int b); /* function declaration */
*/
{
int main()
if(x > y)
{
{
int i, j, result;
return x;
cout<<"Enter 2 numbers that you want to
}
compare...“<<endl;
else
cin>>i>>j;
{
result = large(i, j); /* function call */
return y;
cout<<"The greater number is: “<<result;
}
return 0;
}
}
Function with arguments and no
return value
Here function will accept data from the calling function as there are arguments, however,
since there is no return type nothing will be returned to the calling program. So it’s a one-
way type communication.
Example
#include<stdio.h> void large(int x, int y) /* function definition */
void large(int a, int b); /* function declaration */ {
int main() if(x > y)
{ {
int i, j; cout<<"The greater number is: " <<x;
cout<<"Enter 2 numbers that you want to }
compare..."; else
cin>>i>>j; {
large(i, j); /* function call */ cout<<"The greater number is: “<< y;
return 0; }
} }
Function with no arguments and return value

 In this method, We won’t pass any arguments to the function while defining, declaring or
calling the function.

 This type of functions will return some value when we call the function from main() or any sub
function.

 Function with no arguments means called function does not receive any data from calling
function and function with return value means one result will be sent back to the caller from
the function.
Example
int large() /* function definition */
{
int i, j, greaterNum;
#include<iostream.h>
cout<<"Enter 2 numbers that you want
to
int large(); /* function declaration */
compare...";
cin>>i>>j;
void main()
if(i > j)
{
{
int result;
greaterNum = i;
result = large(); /* function call */
}
cout<<"The greater number is: “<<result;
else
}
{
greaterNum = j;
}
/* returning the result */
return greaterNum;
}
Function with no arguments and no return
value
 Function with no argument means the called function does not receive any data from calling function and
Function with no return value means calling function does not receive any data from the called function.
 So there is no data transfer between calling and called function.
void large() /* function definition */
{
Example int i, j;
cout<<"Enter 2 numbers that you want to compare
include<iostream.h> cin>>i>>j;
if(i > j)
void large(); /* function declaration */ {
cout<<"The greater number is: “<<i;
int main() }
{ else
large(); /* function call */ {
return 0; cout<<"The greater number is: “<<j;
} }
}
#include <stdio.h>
Recursion int factorial(int number);
int main()
The process by which a function calls itself is known as {
recursion. int x = 6;
Two fundamental rules of recursion are cout<<"The factorial of “ <<x<<" is\n“<<
1. Base cases: A recursive function must have some factorial(x);
base cases, which can be solved without recursion. return 0;
2. Making Progress: For the cases that are to be solved }
recursively, the recursive call must always be to a int factorial(int number)
case that makes progress toward a base case. {
if (number == 1)
return (1); /* exiting condition
*/
else
return (number *
factorial(number - 1));
}

The program displays:

The factorial of 6 is 720


POINTERS
n Variable name
Consider the declaration,
10 Value of n

int n=10; 4500 Address of n

This declaration tells the C++ Compiler to:


We can see that the computer has selected
 Allocate space in memory to store the integer value. memory location 4500 to store the value 10.
 Associate the name n with this memory location.
 Store the value 10 at this location. This location 4500 is not a number to be relied
upon, because some other time the computer
may choose a different location for storing the
value 10.

It may be noted that n’s address in memory is a


number.
& and * Operators
There are two operators available in dealing with pointers. They are

& operator (‘Address of’) n p


* operator (‘Value at address’)
10 4500
To understand the use of these operators, consider
4500 3200
the following program.
void main()
{
int n=10; In the above program we have initialized a variable n with
int *p; value 10. As shown in the memory map, the variable n is
p=&n; stored in the location 4500. We can retrieve this location
cout<<“\n Address of n= ”<<&n; number(address) with the help of & operator. That is, the
cout<<“\n Address of n= ”<<p; statement
cout<<“\n Address of p= ”<<&p;
cout<<“\n Value of p= ”<<p; cout<<“\n Address of n= ”<<&n;
cout<<“\n Value of n= ”<<n;
cout<<“\n Value of n= ”<<*(&n); will print the address of n which is 4500.
cout<<“\n Value of n= ”<<*p;
}
Let us go by the meaning of *. It stands for
We can store this address in another variable. In ‘value at address’. Thus, int *p would mean, the
this program, the statement value at address contained in p is an int. The
‘value at address’ operator is also called as
p=&n; indirection operator. Using indirection operator
to access value of a variable is known as
assigns address of n to a variable p. Now p is not dereferencing.
an ordinary variable.
The output of the above program would be:
Ordinary variables are not capable of storing
address of another variable. Address of n= 4500
Address of n= 4500
Hence p should be declared as pointer variable Address of p= 3200
because p contains address of n. Value of p= 4500
Value of n= 10
The statement Value of n= 10
Value of n= 10
int *p;
Note that printing the value of *(&n) is same as
declares p as pointer variable. printing the value of n. Since &n is an address,
dereferencing it with * operator will give the
The meaning of this declaration is that p is going to variable at that address and the variable at that
contain an address of integer variable or p points address is n. Hence writing *(&n) is same as
to an int. writing n.
 Pointers are also variables and hence compiler will #include<iostream.h>
reserve space for them and they will also have some main ( )
address. (
char a= 'b' , *ptr1=&a;
 All pointers irrespective of their base type will int b=52, *ptr2=&b;
occupy some space in memory since all of them float c=412.4,*ptr3=&c;
contain addresses only. double d=182.3,*ptr4=&d;
cout<<“sizeof(ptr1)= “ <<sizeof(ptr1)<<
 Generally 2 bytes are used to store an address (may “sizeof(*ptr1)= \n”<<sizeof(*ptr1);
vary in different computers), so the compiler cout<<“sizeof(ptr2)= “ <<sizeof(ptr2)<<
allocates 2 bytes for a pointer variable. “sizeof(*ptr2)= \n”<<sizeof(*ptr2);
cout<<“sizeof(ptr3)= “ <<sizeof(ptr3)<<
 The size of pointer variable is same for all type of “sizeof(*ptr3)= \n”<<sizeof(*ptr3);
pointers but the memory that will be accessed while cout<<“sizeof(ptr4)= “ <<sizeof(ptr4)<<
dereferencing is different. “sizeof(*ptr4)= \n”<<sizeof(*ptr4);
}
/* Program to print the size of pointer variable and size
of value dereferenced by that pointer* / Output
sizeof(ptr1)=2, sizeof(*ptr1)=1
sizeof(ptr2)=2, sizeof(*ptr2)=2
sizeof(ptr3)=2, sizeof(*ptr3)=4
sizeof(ptr4)=2, sizeof(*ptr4)=8
POINTER TO POINTER
We know that pointer is a variable that holds memory address of another variable.

This pointer variable takes some space in memory and hence it also has an address.

We can store the address of a pointer variable in some other variable, which is known as a pointer to pointer
variable.

Similarly we can have a pointer to pointer to pointer variable and this concept can be extended to any limit, but
in practice 0nly pointer to pointer is used.

Pointer to pointer is generally used while passing pointer variables to functions.

The syntax of declaring a pointer to pointer is -

data type **pointer variable;

Example :

int **pptr;

Here variable pptr is a pointer to pointer and it can point to a pointer pointing to a variable of type int. The double
asterisk used in the declaration informs the compiler that a pointer to pointer is being declared.
Here the variable a is an int, j is pointer to int and k is
Let us consider the following declarations: pointer to pointer.
int a = 10; The following program demonstrates the concept of
int *j = &a; pointer to pointer.
int **k = &j;
#include<iostream.h>
Here type of variable a is int, type of variable j is (int*) or main( )
pointer to int, and type of variable k is (int **) or pointer to {
pointer to int. int a=10;
int *j;
Consider the following memory map: int **k;
j=&a;
k=&j;
a k
cout<<"Address of a = " <<&a<<endl;
j
cout<<"Value of j = Address of a= “<<j<<endl;
10 4500 3200
cout<<"Value of *j = Value of a= “<<*j<<endl;
4500 3200 4850 cout<<"Address of j = “<<&j<<endl ;
cout<<"Value of k = Address of j = “<<k<<endl;
cout<<"Value of *k = Value of j=“<<*k<<endl';
cout<<"Value of **k= Value of a = “<<**k<<endl;
cout<<"Address of k = “<<&k<<endl;
}
REFERENCE VARIABLE
C++ introduces a new kind of variable known as the reference variable.
A references variable provides an alias(alternative name) for a previously defined variable.
For example ,if we make the variable sum a reference to the variable total, then sum and total can be used
interchangeably to represent the variable.
A reference variable is created as follows:
Synatx:
Datatype & reference –name=variable name;
Example:
float total=1500;
float &sum=total;
Here sum is the alternative name for variables total, both the variables refer to the same data object in the memory .
A reference variable must be initialized at the time of declaration .
PARAMETER PASSING MECHANISMS

 Functions can be invoked in three ways: Call by Value , Call by Address and Call by Reference . These
three ways are generally differentiated by the type of values passed to them as parameters.

 The parameters passed to function are called actual parameters whereas the parameters received by
function are called formal parameters.

CALL BY VALUE

 In this parameter passing method, values of actual


parameters are copied to function’s formal  With this method, the changes made to the dummy
parameters and the two types of parameters are variables in the called function have no effect on the
stored in different memory locations. values of actual variables in the calling function.

 So any changes made inside functions are not  In call by values we cannot alter the values of actual
reflected in actual parameters of caller. variables through function calls.

 While calling a function, we pass values of variables


to it. Such functions are known as “Call By Values”.

 In this method, the value of each variable in calling


function is copied into corresponding dummy
variables of the called function.
/* C++ program to illustrate call by value */

#include <iostream.h>
void swapval(int x, int y); /* Function Prototype */

void main()
{ cout<<“x= “<<x<<“y= “<<y<<endl;
int a = 10, b = 20; }

/* Pass by Values */ Output


swapval(a, b);
x=20 y=10
cout<<"a= “<<a<<"b= “<<b<<endl; a=10 b=20
}
/* Swap functions that swaps two values */ Thus actual values of a and b remain
void swapval(int x, int y) unchanged even after exchanging the values
{ of x and y.
int t;

t = x;
x = y;
y = t;
CALL BY ADDRESS
 In this method, both the actual and formal  With this method, using addresses we would have
parameters refer to same locations, so any an access to the actual variables and hence we
changes made inside the function are actually would be able to manipulate them.
reflected in actual parameters of caller.
 In call by address we can alter the values of
 While calling a function, instead of passing the variables through function calls.
values of variables, we pass address of
variables(location of variables) to the function  Pointer variables are necessary to define to store
known as Call By address. the address values of variables.

 In this method, the address of actual variables in


the calling function are copied into the dummy
variables of the called function.
/* Function to swap two variables by references */
void swapref(int * x, int * y)
/* C++ program to illustrate Call by Address */ {
int t;
#include <iostream.h>
void swapref(int*, int*); /* Function Prototype */ t = *x;
int main() *x = *y;
{ *y = t;
int a = 10, b = 20; cout<<“x= “<<*x<<“y= “<<*y<<endl;
}
/* Pass address */
swapref(&a, &b); Output

cout<<"a= “<<a<<"b= “<<b<<endl; x=20 y=10


a=20 b=10
return 0;
} Thus actual values of a and b get changed after
exchanging values of x and y.
CALL BY REFERENCE
 The call by reference method of passing  To pass the value by reference, argument reference
arguments to a function copies the reference of is passed to the functions just like any other value.
an argument into the formal parameter.
 So accordingly you need to declare the function
 Inside the function, the reference is used to parameters as reference types as in the following
access the actual argument used in the call. function swapref(), which exchanges the values of
the two integer variables pointed to by its
 This means that changes made to the parameter arguments.
affect the passed argument.
/* Function to swap two variables by references */
void swapref(int &x, int &y)
/* C++ program to illustrate Call by Reference */ {
int t;
#include <iostream.h>
void swapref(int &, int &); /* Function Prototype */ t = x;
int main() x = y;
{ y = t;
int a = 10, b = 20; cout<<“x= “<<x<<“y= “<<y<<endl;
}
/* Pass reference */
swapref(a, b); Output

cout<<"a= “<<a<<"b= “<<b<<endl; x=20 y=10


a=20 b=10
return 0;
} Thus actual values of a and b get changed after
exchanging values of x and y.
 The above prototype declares a default value of 0.15
DEFAULT ARGUMENTS to the argument rate.

 C++ allows us to call a function with out specifying all its  A subsequent function call like
arguments. value=amount(5000,7); //one argument missing

 In such cases, the function assigns a default value to the passes the value of 5000 to principle and 7 to
parameter which does not have a matching arguments in the period and then lets the function, use default
function call. value of 0.15 for rate.

 Default values are specified when the function is declared .  The call:-

 The compiler looks at the prototype to see how many value=amount(5000,5,0.12);


arguments a function uses and alerts the program for possible //no missing argument passes an explicit value
default values. of //0.12 rate.

 Example:  One important point to note is that only the trailing


arguments can have default values.
 float amount (float principle, int period ,float rate=0.15);
 That is, we must add default from right to left.
 The default value is specified in a manner syntactically similar to
a variable initialization .  We cannot provide a default to a particular argument
in the middle of an argument list.
amount=value(5000.00,5);
Example:- int mul(int i, int j=5,int k=10);//illegal
cout<<”\n final value=”<<amount<<endl;
int mul(int i=0,int j,int k=10);//illegal
printline(‘=’);
int mul(int i=5,int j);//illegal
}
int mul(int i=2,int j=5,int k=10);//illegal
//function definitions
float value (float p,int n, float r)
Default arguments are useful in situation whose
{
some arguments always have the some value.
float si;
si=(p*n*r)/100;
For example, bank interest may retain the same
return(si);
for all customers for a particular period of
}
deposit.
void printline (char ch,int len)
{
#include<iostream.h>
for(inti=l;i<=len;i++)
#include<stdio.h>
cout<<ch<<endl;
mainQ
}
{
float amount;
output:-
float value(float p,int n,float r=0.15);
****************
void printline(char ch=’*’,int len=40);
final value=10056.71613
printline( );
================
const Argument
In C++, an argument to a function can be declared as const as shown below.
int strlen(const char *p);
int length(const string &s);
The qualifier const tells the compiler that the function should not modify the argument.
The compiler will generate an error when this condition is violated.
This type of declaration is significant only when we pass arguments by reference or pointers.
INLINE FUNCTION:  The above inline function can be
invoked by statements like Example:
To eliminate the cost of calls to small functions c=cube(3.0);
C++ proposes a new feature called inline d=cube(2.5+1.5); #include<iostream.h>
function.  Remember that the inline keyword #include<stdio.h>
merely sends a request, not a
An inline function is a function that is expanded command to the compiler. inline float mul(float x, float y)
inline when it is invoked. {
 The compiler may ignore this return(x*y);
That is the compiler replaces the function call request if the function definition is }
with the corresponding function code. too long or too complicated and
compile the function as a normal inline double div(double p,
The inline functions are defined as follows:- function. double q)
inline function-header {
{  Some of the situations where inline return(p/q);
function body; expansion may not work are: }
} 1. For functions returning values if a
Example: loop, a switch or a go to exists. main( )
2. for function s not returning values, if {
inline double cube (double a) a return statement exists. float a=12.345;
{ 3. if functions contain static variables. float b=9.82;
return(a*a*a); 4. if inline functions are recursive,.
} cout<<mul(a,b)<<endl;
cout<<div
(a,b)<<endl;
FUNCTION OVERLOADING
For example an overloaded add() function handles
 Overloading refers to the use of the same thing for different types of data as shown below.
different purposes .
//Declaration
 C++ also permits overloading functions. int add(int a, int b); //prototype 1
int add (int a, int b, int c); //prototype 2
 This means that we can use the same function name to double add(double x, double y); //prototype 3
creates functions that perform a variety of different tasks. double add(double p , double q); //prototype 4

 This is known as function polymorphism in oops. //function call


cout<<add(5,10); //uses prototype 1
 Using the concepts of function overloading , a family of cout<<add(15,10.0); //uses prototype 4
functions with one function name but with different cout<<add(12.5,7.5); //uses prototype 3
argument lists in the functions call . cout<<add(5,10,15); //uses prototype 2

 The correct function to be invoked is determined by


checking the number and type of the arguments but not
on the function return type.
A function call first matches the prototype having the same no and #include<iostream.h>
type of arguments and then calls the appropriate function for int volume(int);
execution. double volume( double , int );
double volume(long int ,int ,int);
The function selection invokes the following steps:- main( )
{
a) The compiler first tries to find an exact match in which the types cout<<volume(10)<<endl;
of actual arguments are the same and use that function . cout<<volume(2.5,3)<<endl;
cout<<volume(10,5,7)<<endl;
b) If an exact match is not found the compiler uses the integral }
promotions to the actual arguments such as : int volume( int s)
char to int {
float to double return (s*s*s); //cube
to find a match }
double volume( double r, int h)
c)When either of them fails ,the compiler tries to use the built in {
conversions to the actual arguments and them uses the function return(3.1416*r*r*h); //cylinder
whose match is unique . }
long volume (long int l, int b, int h)
If the conversion is possible to have multiple matches, then the {
compiler will give error message. return(l*b*h); //cylinder
}
Example:
long square (long n);
double square(double x);
Thank you..
END OF MODULE 2..

You might also like