Вы находитесь на странице: 1из 27

Ravi kumar A.V. lect..

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.

Need for a Function

When programs become large, a single list of instruction becomes difficult to


understand. For this reason, functions are used. A function has a cleared defined
purpose and has an interface to other functions in the program. A group of functions
together form a large entity called a module.

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:

Return_type function_name(input data type and name list)


{

// body of function

return_type: the data type of the variable passed back to the calling function via a
return statement

arguments: input values for a function; also known as input argument

S.J.B.I.T E&C Dept. 1


Ravi kumar A.V. lect.. E&C

The following program illustrates the usage of a function:

//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;
}

//Function definition for add


void add()
{
int iNum1, iNum2, iNum3;
cin>>iNum1;
cin>>iNum2;
iNum3 = iNum1 + iNum2;
cout<<"The sum of the two numbers is"<<iNum3<<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.

The sample output of Program 7.1 si:

Calling function add()


Input two numbers
10
20
The sum of the two numbers is 30
A return from add() function

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.

S.J.B.I.T E&C Dept. 2


Ravi kumar A.V. lect.. E&C

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:

Just as any variable is declared in a program before it is used, it is necessary to


declare or prototype a function to inform the compiler that the function would be
referenced at a later point in the program.

In Program 7.1, the statement:

void add();

is a function declaratoin or a prototype.

Defining a Function

The function definition contains the code for the function. The function definition
for add() in Program 7.1 is:

//Function definition for add


void add()
{
int iNum1, iNum2, iNum3;
cin>>iNum1;
cin>>iNum2;
iNum3 = iNum1 + iNum2;
cout<<"The sum of the two numbers is"<<iNum3<<endl;
}

A function declaration can be avoided if the function definition appears before the
first call to the function.

S.J.B.I.T E&C Dept. 3


Ravi kumar A.V. lect.. E&C

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;

S.J.B.I.T E&C Dept. 4


Ravi kumar A.V. lect.. E&C

cin>>iNum1;
cin>>iNum2;
add(iNum1, iNum2); //Passing two values to the function add()
}

Calling Function:

In C++ programs, functions that have arguments can be invoked by:

> 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

The following program illustrates the invoking of a function 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)

S.J.B.I.T E&C Dept. 5


Ravi kumar A.V. lect.. E&C

{
int iTemp;
iTemp = iNum1;
iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}

The sample output of Program 7.4 is:

Input two numbers


15
25
In swap 25 15
In main 15 25

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.

This is depicted in the following figures(refer Figure 7.1 and 7.2).

iVar1 iVar2 iVar1 iVar2


15 25 15 25

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

S.J.B.I.T E&C Dept. 6


Ravi kumar A.V. lect.. E&C

the called function swap() as they occupy distinct memory locations.

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.

The following program illustrates the use of reference variables:

//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;
}

In Program 7.5, the statement

number++;

S.J.B.I.T E&C Dept. 7


Ravi kumar A.V. lect.. E&C

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.

The output of program 7.5 is:

Number is 5
Increasing the number........
NUmber now is 6
Reference now is 7
Number now is 7

A reference variable can be initialized only when it is declared.

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

//This program swaps the values in the variable using function


containing reference arguments
#include<iostream.h>
void swap(int *, int *);
void main()
{
int iVar1, iVar2;
cout<<"Enter two numbers "<<endl;
cin>>iVar1;
cin>>iVar2;
swap(&iVar1,& iVar2);

S.J.B.I.T E&C Dept. 8


Ravi kumar A.V. lect.. E&C

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;
}

//program 7.5b

//This program calculate the volume of the cylinder

#include<iostream.h>
#define pi 3.141

void get_dim(float *, float *);

void cal_vol(float, float);

void main()
{

float radius,hight,volume;

get_dim( & radius , & hight);

volume = cal_vol( radius,hight);

cout << “cylinder volume =” << volume;

void get_dim( float *r_ptr ,float *h_ptr)

{
float r,h;

S.J.B.I.T E&C Dept. 9


Ravi kumar A.V. lect.. E&C

cout << “enter the radius and hight of cylinder\n”;

cin >> r >> h;

*r_ptr= r;

*h_ptr= h;

float cal_vol ( float rad, float hgt)

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;
}

void swap(int &iNum1, int &iNum2)


{
int iTemp;
iTemp = iNum1;

S.J.B.I.T E&C Dept. 10


Ravi kumar A.V. lect.. E&C

iNum1 = iNum2;
iNum2 = iTemp;
cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;
}

Reference arguments are indicated by an ampersand (&) preceding the argument:

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:

void swap(int &iNum1, int &iNum2)

The ampersand sign is not used during the function call:

swap(iVar1, iVar2);

The sample output of Program 7.6 is:

Enter two numbers


12
24
In swap 24 12
In main 24 12

In Program 7.6, the values in the variables iVar1 and iVar2 in the calling program are
swapped.

This is depicted in Figure 7.3

iVar1 iVar2
24 12
iNum1 iNum2

Figure 7.3 After Swap() Function is


Executed

S.J.B.I.T E&C Dept. 11


Ravi kumar A.V. lect.. E&C

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.

A function that assigns default arguments is illustrated in the following code


segment:

int add(int iNum1 = 10, int iNum2 = 20)


{
return iNum1 + iNum2;
}

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.

S.J.B.I.T E&C Dept. 12


Ravi kumar A.V. lect.. E&C

The following program illustrates the use of default arguments:

//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);
}

The output of Program 7.7 is:

Sum is 30
Sum is 12

return Values from Functions

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;

S.J.B.I.T E&C Dept. 13


Ravi kumar A.V. lect.. E&C

iSum1 = add(iVar1, iVar2);


cout<<"The sum of the two numbers is "<<iSum1<<endl;
}
int add(int iNum1, int iNum2)
{
return iNum1+iNum2;
}

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:

iSum1 = add(iVar1, iVar2)

causes the variable iSum1 to be assigned the value returned by the function add().

The sample output of Program 7.8 is:

Enter two numbers


23
37
The sum of the two number is 60

Passing Arrays to Functions

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:

stringfunc(int number_list[]) //No subscript

S.J.B.I.T E&C Dept. 14


Ravi kumar A.V. lect.. E&C

OR

stringfunc(int number_list[10]) //Same size as num_array


{

OR

stringfunc(int *number_list) //int type pointer


{

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.

Overloading Functions in C++

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.

The following program illustrates a function using different type of parameters:

//Program 7.9
//This program calculates sum of two numbers
#include<iostream.h>
int add(int iNum1, int iNum2)

S.J.B.I.T E&C Dept. 15


Ravi kumar A.V. lect.. E&C

{
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.

If the function calls itself directly, then it is known as direct recursion

E.g.
Void myfun()
{
----------------
-------- ------
myfun();

S.J.B.I.T E&C Dept. 16


Ravi kumar A.V. lect.. E&C

……………..
}
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().

//program to find the factorial of number

#include<iostream.h>
int fact ( int n)
{
if ( n== 0)
return 1;
return n * fact (n-1);
}

S.J.B.I.T E&C Dept. 17


Ravi kumar A.V. lect.. E&C

void main ()
{
int n ;
cout << “ enter the value of n”;
cin >> n;

if (n < 0)

cout << “ invalid input”;


else
cout << “ factorial of number” << n << “is”<< n << fact(n);
}

The output would be:


Enter the value of n 6
Factorial of number 6 is 720

//program to find the nth Fibonacci number


#include<iostream.h>
int fibo ( int n)
{
if ( n== 1)
return 0;
if ( n== 2)
return 1;

return fibo (n-1) + fibo (n-2);

S.J.B.I.T E&C Dept. 18


Ravi kumar A.V. lect.. E&C

void main ()
{
int n ;
cout << “ enter the value of n”;
cin >> n;

if (n < 0)

cout << “ invalid input”;


else
cout << “ Fibonacci number is ”<< fibo(n);
}

the output would be:


enter the value of n 10
Fibonacci number is 34

// Program to implement Bubble sort

#include<iostream.h>
#include<iomanip.h>

void input(int a[],n)


{

for(int i=0;i<n;i++)
x[i]=a[i];
}

void sort(int x[ ], int items)


{

S.J.B.I.T E&C Dept. 19


Ravi kumar A.V. lect.. E&C

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;
}
}
}
}

void display(int x[ ], int items)


{
for(int i=0;i<items;i++)
cout<<" "<<x[i];
}

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

Enter how many elements

S.J.B.I.T E&C Dept. 20


Ravi kumar A.V. lect.. E&C

6
Enter 6 elements
34 18 22 11 88 13

Output
11 13 18 22 34 88

// Program to implement Linear search

#include<iostream.h>
#include<iomanip.h>
void input(int a[ ],int items)
{
for(int i=0;i<items;i++)
x[i]=a[i];
}

int search(int number, int items)


{
for(int i=0;i<items;i++)
{
if(number==x[i])
return i+1;
}

S.J.B.I.T E&C Dept. 21


Ravi kumar A.V. lect.. E&C

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

// Program to illustrate use of arrays with pointers

#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;
}

S.J.B.I.T E&C Dept. 22


Ravi kumar A.V. lect.. E&C

void add(int *ptr)


{
for(int i=0;i<5;i++)
{
*ptr=*ptr+5;
ptr++;
}
}

Test data

Enter 5 numbers
12345

Output
The values in a after executing function
6 7 8 9 10

// program to check whether the string is palindrome or not


If not make it a palindrome by adding to its end

#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])

S.J.B.I.T E&C Dept. 23


Ravi kumar A.V. lect.. E&C

{
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

Enter string to check


mouse

Output
Given string is converted to palindrome
mousesuom

// Program to sort given names

#include<iostream.h>
#include<string.h>
#include<conio.h>

int main()
{
char name[5][20],temp[20];

S.J.B.I.T E&C Dept. 24


Ravi kumar A.V. lect.. E&C

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

The sorted names are


cobol
cplusplus
java
oracle
perl

S.J.B.I.T E&C Dept. 25


Ravi kumar A.V. lect.. E&C

// Program to find the maximum sum of consecutive positive integers


#include <iostream.h>
#include<conio.h>
int main()
{
int a[50];
int i,n;
int sum=0,maxsum=0;
clrscr();
cout<<"Enter how many numbers \n";
cin>>n;
for(i=0;i<n;i++)
cin >> a[i];
for(i=0;i<n;i++)
{
if(a[i]> 0)
sum = sum + a[i];
if(sum>maxsum)
maxsum=sum;
if(a[i]<0)
sum=0;
}
cout<<maxsum;
return 0;
}

Test data

Enter how many numbers


12
-5 1 2 3 -7 4 6 -1 1 1 1 1

Output
10

// Program to find whether a given number is palindrome or not


If not make it palindrome by adding to its end

#include <iostream.h>

int main(void)
{
long n,i,j,sum=0;
cout<<"Enter any number \n";

S.J.B.I.T E&C Dept. 26


Ravi kumar A.V. lect.. E&C

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

Enter any number


121
Output
palindrome

Test data 2

Enter any number


123
Output
new palindrome 12321

S.J.B.I.T E&C Dept. 27

Вам также может понравиться