Beruflich Dokumente
Kultur Dokumente
E&C
FUNCTION
Modular Approach
Functions are the building blocks of C++ programs. A function groups a number of
program statements into a single unit. This unit can be invoked from other parts of
the program.
Another reason for using functions is to reduce the size of the program. Any
sequence of instructions that is repeated in a program can be grouped together to
form a function. The function code is stored in only one place in the memory even
though the function may be executed a repeated number of times.
BASIC FORMAT:
// body of function
return_type: the data type of the variable passed back to the calling function via a
return statement
//Program 7.1
//This program uses a function to calculate the sum of two numbers
#include<iostream.h>
void add();
void main()
{
cout<<"Calling function add()"<<endl;
add(); //A call to the function add(), while calling a function the
command is terminated with a ';'
cout<<"A return from add() function"<<endl;
}
In Program 7.1, the function add() is invoked from the function main(). The control
passes to the function add(), and the body of function is executed. The control then
returns to main() and the remaining code of main() is executed.
In Program 7.1, the function main(), which invokes the function add(), is called the
calling function, and the function add() is the called function.
Calling function: when one function uses( or invoked ) a second function, the
first function is the calling function.
Called function: when one function uses ( or invoked ) a second function , the
second function is the called function.
Function prototype:
void add();
Defining a Function
The function definition contains the code for the function. The function definition
for add() in Program 7.1 is:
A function declaration can be avoided if the function definition appears before the
first call to the function.
Program 7.1 can be modified to avoid function declaration in the following way:
//Program 7.2
//This program uses a function to calculate the sum of two numbers
#include<iostream.h>
void add()
{
int iNum1, iNum2, iNum3;
cin>>iNum1;
cin>>iNum2;
iNum3 = iNum1 + iNum2;
cout<<"The sum of the two numbers is"<<iNum3<<endl;
}
void main()
{
cout<<"Calling function add()"<<endl;
add(); //A call to the function add(), while calling a function the
command is terminated with a ';'
cout<<"A return from add() function"<<endl;
}
Function Arguments
Argument(s) of a function is(are) the data the function receives when called from
another function. It is not always necessary for a function to have arguments. The
function add() in Program 7.1 did not contain any arguments. The add() function in
Program 7.1 can be modified to accept two arguments in the following way:
//Program 7.2
#include<iostream.h>
vodi main(int iVar1, int iVar2) //Function containing two arguments
{
int iVar3 = iVar1 + iVar2;
cout<<"The sum of the two numbers is: "<<iVar3<<endl;
}
void main()
{
int iNum1, iNum2;
cout<<"Input tow numbers "<<endl;
cin>>iNum1;
cin>>iNum2;
add(iNum1, iNum2); //Passing two values to the function add()
}
Calling Function:
> Value
> Reference
Call by Value
In the Call by Value method, the called function creates new variables to store the value
of the arguments passed to it.
When the data is passed to a function, the value of the variable is copied into the input
parameter variable of the called function. This type of a function call is known as a call
by value
//Program 7.4
//This function swaps the value of two variable
#include<iostream.h>
void swap(int, int);
void main()
{
int iVar1, iVar2;
cout<<"Input two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}
void swap(int iNum1, int iNum2)
{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}
In Program 7.4, values entered for the variables iVar1 and iVar2 are passed to the
function swap(). When the function swap() is invoked, these values get copied into the
memory locations of the parameters iNum1 and iNum2, respectively.
15 25 25 15
iNum1 iNum2 iNum1 iNum2
Fig 7.1 When swap() Funtion Fig 7.2 After the swap()
is invokded Function is Executed
Therefore, the variables in the calling function main() are distinct from the variables in
In Program 7.4, the function arguments are passed by value. When arguments are passed
by value, the called function creates new variables of the same data type as the
arguments passed to it. The values of these arguments are copied into the newly created
variables. Passing arguments by value is useful when the function does not need to
modify the values of the original variables in the calling program. Therefore, the values
of the variables in the calling functions do not get affected when the arguments are
passed as values.
Reference Variable:
A reference variable provides an alias- an alternate name- for the variable. A reference
variable is declared by preceding the variable name with an ampersand (&). The
following statements declare a reference variable called refer.
int num;
int &refer = num;
In the statements given above, refer is a reference variable or alias to the variable num.
A reference declaration allows a variable name and the reference name to be used
interchangeably. Both the variable and its reference share the same memory address.
//Program 7.5
//This program illustrates the use of reference variables
#include<iostream.h>
void main()
{
int number = 5;
int &ref = number;
cout<<"Number is "<<number<<endl;
cout<<"Incresing the number......"<<endl;
number++;
cout<"Number now is "<<number<<endl;
ref++;
cout<<"Reference now is "<<ref<<endl;
cout<<"Number now is "<<number<<endl;
}
number++;
increments the value of the variable number by 1, the value of the variable number
therefore becomes 6. The statement:
ref++;
again increments the value of the variable number by 1 because ref points to the same
memory location as number.
Number is 5
Increasing the number........
NUmber now is 6
Reference now is 7
Number now is 7
Call by Reference
the address of the data variable is passed to a function. The address is copied into a
pointer variable that belongs to the called function. The called function access the
calling function variable via the indirection operator and pointer
Note: if the calling function must return several data item to a calling function, the
programmer can use the call by reference technique.
//program 7.5b
//program 7.5b
#include<iostream.h>
#define pi 3.141
void main()
{
float radius,hight,volume;
{
float r,h;
*r_ptr= r;
*h_ptr= h;
return( pi * rad*rad*hgt);
OR other method:
A reference provides an alias- an alternate name- for the variable. While passing
reference arguments, a reference to the variable in the calling program is passed.
Program 7.4 can be modified using reference arguments in the following way:
//Program 7.6
//This program swaps the values in the variable using function
containing reference arguments
#include<iostream.h>
void swap(int &iNum1, int &iNum2);
void main()
{
int iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(iVar1, iVar2);
cout<<"In main "<<iVar1<<" "<<iVar2<<endl;
}
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}
int &iNUm1;
In Program 7.6, the ampersand (&) indicates that iNum1 is an alias for iVar1 which is
passed as an argument.
The function declaration must have an ampersand following the data type of the
argument:
swap(iVar1, iVar2);
In Program 7.6, the values in the variables iVar1 and iVar2 in the calling program are
swapped.
iVar1 iVar2
24 12
iNum1 iNum2
Default Arguments
Default Arguments
C++ allows a function to assign default values to parameters. The default value
is assigned when no argument corresponding to that parameter is specified in
the call to that function.
In the above code segment, if the add() function is invoked without arguments,
then the default values of 10 and 20 are assigned to iNum1 and iNum2,
repectively. If values are passed to the function, then corresponding values are
assigned to iNum1 and iNum2.
//Program 7.7
//This program illustrates the use of default arguments
#include<iostream.h>
void add(int iNum1 = 10, int iNum2 = 20)
{
cout<<"Sum is "<<iNum1+iNum2<<endl;
}
void main()
{
int var1 = 5, var2 = 7;
add();
add(var1, var2);
}
Sum is 30
Sum is 12
When a function completes its execution, it can return a single value to the calling
program, which can be trapped when the calling function needs the result of the
called function. The following program illustrates a function that returns a value:
//Program 7.8
//This program uses a function to add two numbers and returns the
sum to the calling program
#include<iostream.h>
int add(int, int); //This function returns a value of type int
void main()
{
int iSum1, iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
When a function returns a value, the data type of the value must be specified. In
Program 7.8, the type int is placed before the function add(). Function in the earlier
program returned no value, therefore the return type was void.
The statement:
causes the variable iSum1 to be assigned the value returned by the function add().
Arrays are inherently passed to functions by the call by address method. For
instance, if an array num_array of size ten is to be passed to a function called
stringfunc(), then it would be passed in the following way:
stringfunc(num_array);
Recall that num_array is actually the address of the first element of the array,
num_array[0].
The parameter of the called function, say number_list, can be declared in any of the
following ways:
OR
OR
While passing arrays to functions, the address of the array is passed from the calling
function. Since the address of the array is always passed to a function, it is easy to
alter the contents of the array directly in the called function. Therefore, arrays do not
have to be returned from a function explicitly using the return statement.
Function overloading is the process of using the same name for two or more
functions. Each redefinition of a function must use different type of parameters, or
different sequence of parameters, or different number of parameters. The number,
type and sequence of parameters for a function is called the function signature.
//Program 7.9
//This program calculates sum of two numbers
#include<iostream.h>
int add(int iNum1, int iNum2)
{
return iNum1+iNum2;
}
float add(float fNum1, float iNum1)
{
return fNum1+iNum1;
}
void main()
{
cout<<add(20, 30)<<endl; //The function add(int, int) is called
float i= 9.6;
float b= 8.8;
cout<<add(i, b)<<endl; //The function add(float, float) is called
}
Two functions differing only in their return type cannot be overloaded. For example,
overloading int add(int, int) and float add(int, int) would flag an error.
Recursion :
if a function calls itself then it is known as recursive function.
E.g.
Void myfun()
{
----------------
-------- ------
myfun();
……………..
}
here, the function myfun() is calling itself directly
if the function calls itself through another function, then it is known as indirect
recursion .
E.g.
Void myfun()
{
---------------
--------------
fun();
--------------
-------------,
void fun()
{
-----------
------------
myfun();
------------
------------
}
here the function myfun() is calling the function fun(), which in turn calls myfun().
#include<iostream.h>
int fact ( int n)
{
if ( n== 0)
return 1;
return n * fact (n-1);
}
void main ()
{
int n ;
cout << “ enter the value of n”;
cin >> n;
if (n < 0)
void main ()
{
int n ;
cout << “ enter the value of n”;
cin >> n;
if (n < 0)
#include<iostream.h>
#include<iomanip.h>
for(int i=0;i<n;i++)
x[i]=a[i];
}
for(int i=0;i<items;i++)
{
for(int j=0;j<items-(i+1);j++)
{
if(x[j]>x[j+1])
{
int temp;
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
}
}
}
}
int main()
{
int a[ ],n;
cout<<"\n Enter how many elements";
cin>>n;
cout<<"\n Enter "<<n<<"elements";
for(int i=0;i<n;i++)
cin>>a[i];
input(a,n);
sort(a,n);
display(a,n);
return 0;
}
Test data
6
Enter 6 elements
34 18 22 11 88 13
Output
11 13 18 22 34 88
#include<iostream.h>
#include<iomanip.h>
void input(int a[ ],int items)
{
for(int i=0;i<items;i++)
x[i]=a[i];
}
return 0;
}
void main()
{
int a[ ],n,temp;
cout<<"\n Enter how many elements \n";
cin>>n;
cout<<"\n Enter "<<n<<"elements";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"\n Enter search number :";
cin>>temp;
void input(a,n);
int position=search(temp,n);
if(position!=0)
cout<<"\n Search number is present and its position:"<<position;
else
cout<<"\n search number is not present";
}
Test data
Enter how many elements
6
Enter 6 elements
23 32 11 67 33 12
Enter search number : 11
Output
Search number is present and its position : 3
#include<iostream.h>
void add(int *);
int main()
{
int a[5],i;
cout<<" Enter 5 numbers \n";
for(i=0;i<5;i++)
cin>>a[i];
add(a);
cout<<"The values in a after executing function \n";
for(i=0;i<5;i++)
cout<<" "<<a[i];
return 0;
}
Test data
Enter 5 numbers
12345
Output
The values in a after executing function
6 7 8 9 10
#include<iostream.h>
int main()
{
char str[80],temp[80];
int i=0,n=0,flag;
cout<<"Enter string to check \n ";
cin>>str;
while(str[i]!='\0')
{
++n;
++i;
}
for(i=0;i<n/2;i++)
{
if(str[i]!=str[n-i-1])
{
flag=0;
break;
}
else flag =1;
}
if(flag==1)
cout<<"\n Given string is palindrome";
else
{
for(i=0;i<n-1;i++)
str[n+i]=str[n-i-2];
str[n+i]='\0';
cout<<"\n Given string is converted to palindrome";
cout<<str;
}
return 0;
}
Test data 1
Enter string to check
madam
output
Given string is palindrome
Test data 2
Output
Given string is converted to palindrome
mousesuom
#include<iostream.h>
#include<string.h>
#include<conio.h>
int main()
{
char name[5][20],temp[20];
int i,j;
clrscr();
cout<<"Enter 5 names \n";
for(i=0;i<5;i++)
cin>>name[i];
for(i=0;i<4;i++)
{
for(j=i+1;j<5;j++)
{
if(strcmp(name[i],name[j])>0)
{
strcpy(temp,name[i]);
strcpy(name[i],name[j]);
strcpy(name[j],temp);
}
}
}
cout<<"The sorted names are \n";
for(i=0;i<5;i++)
cout<<name[i]<<"\n";
return 0 ;
}
Test data
Enter 5 names
java
oracle
cplusplus
perl
cobol
Output
Test data
Output
10
#include <iostream.h>
int main(void)
{
long n,i,j,sum=0;
cout<<"Enter any number \n";
cin>>n;
j=n;
while(j)
{
sum =sum*10+j%10;
j /=10;
}
if(sum==n)
cout<<"\n palindrome";
else
{
i=n;
n/=10;
while(n)
{
i= i*10+n%10;
n /=10;
}
cout<<"\n new palindrome"<<i;
}
return 0;
}
Test data 1
Test data 2