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