Sunteți pe pagina 1din 31

CHAPTER 5

Functions
5.1 WHAT IS A FUNCTION?
A function can be equated to a "blackbox" to which one or more input values are passed, some
processing done, and output value(s) is(are) then returned automatically.
Figure 5.1 illustrates this sequence when a function named sqrt is called. The value of x (16.0)
is the function input, and the function result or output is the square root of 16.0, i.e. 4.0.
Figure 5.1
Function sqrt
as a "Black
Box"
5.1.1 Functions as Program Building Blocks
Programmers use functions like building blocks to construct large programs. Arguments of a
function are used to pass information into the function subprogram from the main function and to
return to the calling function multiple results computed by the function subprogram. Arguments
that carry information from the main function into the function subprogram are called input argu-
ments or parameters. Arguments that return results to the main function are called output argu-
ments.
Figure 5.2 shows a function with multiple inputs and outputs.
The most fundamental idea in problem solving is dividing a problem into subproblems and
solving each subproblem independently. In attempting to solve a subproblem at one level, we
often introduce further subproblems at a lower level. This is shown in Example 1.
result is 4.0
x is 16.0
square root
computation
function sqrt
bpbonline all rights reserved
96 Programming in C++ Part I
Figure 5.2
Function with
multiple
Inputs and
Outputs
Exa mp le 1
Suppose you want to draw simple diagrams or figures shown in Figure 5.3. The figure on the left
consists of a triangle without its base on top of a rectangle. The figure on the right consists of a
pattern consisting of a circle, a triangle and a triangle without its base.
o
u
t
p
u
t
s s
p
t
u
n
i
function
Figure 5.3
House and
Stick Figure
We should be able to draw both diagrams using the four basic graphical components shown in
Figure 5.4. Initially, we shall focus on the stick figure. We can divide the problem of drawing this
figure into the following three sub problems:
(a) Draw a circle
(b) Draw a triangle
(c) Draw intersecting lines
The sub problem of step (b) containing triangle can be further divided into following subproblems,
viz.,
(i) draw intersecting lines
(ii) draw a base
*
*
*
*
*
bpbonline all rights reserved
Part I Functions 97
Figure 5.4
Basic graphical
components to
make House
and Stick
Thus the whole problem can be represented by drawing the block diagram shown in Figure
5.4. As we trace down this diagram, we go from an abstract original problem to a detailed sub-
problem. The original problem is shown at the top as level 0 in Figure 5.5. The major subproblems
appear at level 1. The different subproblems resulting from the refinement of a level 1 step are
shown at level 2 and are connected to their level subproblems. Thus the diagram shows that the
a circle
*
*
*
*
*
a base line
parallel lines
intersecting lines
Figure 5.5
Block diagram
for drawing
stick figure
Draw a
figure
triangle
Draw a Draw a
circle
intersecting
Draw
lines
base
Draw a
Draw
intersecting
lines
level
0
level
1
level
2
original
problem
detailed
subproblems
bpbonline all rights reserved
98 Programming in C++ Part I
subproblem Draw a triangle (at level 1) is dependent on the solutions to the subproblems Draw
intersecting lines and Draw a base (both at level 2). The solution of such type of problems can
easily be carried out using step-down approach.
C ++ Func tion
A C++ function is a grouping of program statements into a single unit to carry out tasks at a given
level. Each C++ function can be activated through the execution of a function call.
If we assume that we have functions available that implement each of the level 2 subproblems
of Figure 5.5, we can use the following program segment to implement the level 1 subproblem
Draw a triangle.
/* Draw a triangle */
draw_intersect();
draw_base();
The above program segment contains two function call statements. During program execution,
the function call statement
draw_intersect();
causes the statements contained in the body of function draw_intersect to be executed.
The program shown in Figure 5.6 also contains another function namely draw_circle. This
function call causes the statements contained in the body of the function draw_circle to be
executed.
When we run the program, the first statement in the main function body (the call to
draw_circle) is the first statement to be executed. When the computer executes a function call
statement, it transfers control to the function that is referenced.
After the last statement in the function body is executed, control returns to the main function.
After the return to the main function, the next statement will be executed (namely the call to
draw_intersect).
The function declarations must appear before any call to the functions. Any of the three func-
tions may be declared first. Their order of execution is determined by the order of function call
statements in the body of the main function. The output of the program given in Figure 5.6 is
shown in Figure 5.7.
The definition of a simple function like draw_circle is similar to the definition of a main func-
tion. It consists of the name of the function followed by the function body. It is desirable to place a
block comment explaining the purpose of the function immediately before the functions name.
The definition of the function (prototype) draw_circle consists of the keyword void, the function
name draw_circle, and then the keyword void again in parentheses.
The result of a function is referred to as its return type. A function that does not yield a value
has a return type of void. The actual actions a function performs are specified in the body of the
function. The function body always starts with the opening brace "{" and ends with the closing
brace "}". Each function body may contain declaration for its own variables. These variables are
considered local to the function. In other words, they can be referenced only within the function.
bpbonline all rights reserved
Part I Functions 99
/* Draw a stick figure */
#include<iostream.h>
#include<stdio.h>
/* Draws a circle */
void draw_circle (void)
{
cout <<" * \n";
cout <<" * *\n";
cout <<" * * \n";
}
/* Draws intersecting lines */
void draw_intersect (void)
{
cout << " / \\ \n";
cout << " / \\ \n";
cout << "/ \\ \n";
}
/* Draws a base line */
void draw_base (void)
{
cout << "-------\n";
}
main (void)
{
/*Draw a circle. */
draw_circle();
/* Draw a triangle */
draw_intersect();
draw_base();
/* Draw intersecting lines. */
draw_intersect();
return(0);
}
Figure 5.6 Program for drawing stick picture
Why Use Func tion?
(a) The use of functions enables us to write our program in logically independent sections in
the same way as we develop the solution algorithm.
(b) Functions may be executed more than once in a program. Also if you have written and
tested a function subprogram, you may use it in other programs or other functions. The
functions we created for stick-figure program in Example 1 could easily be used in pro-
grams that draw other diagrams.
bpbonline all rights reserved
100 Programming in C++ Part I
Figure 5.7
Output of stick figure
5.1.2 Classification of Functions
Functions are of two types. These are:
(a) Built-in Functions or Library functions
(b) User Defined Functions
5.1.3 Built-in Functions
Many of the operations, like taking the square root of a number, sine value of a number etc., will
be frequently used by many programmers in their programs. Writing a program to find the square
root of a number or sine value of a number every time in each program by individual programmers
is an unnecessary and tiresome job. Such operations are programmed in the form of standard
functions and stored in C++ library, so that they can be called in any program. These functions are
called library functions or built-in functions. Table 5.1 shows some of the commonly used mathe-
matical built-in library functions.
Table 5.1 Some Mathematical Built-in Library Functions
Function Library File Purpose: Example Argument(s) Result
abs(x) <stdlib.h> Returns the absolute value of its integer int int
argument:
if x is -5, abs(x) is 5
ceil(x) <math.h> Returns the smallest whole number that is double double
not less than x:
if x is 45.23, ceil(x) is 46.0
(Contd...)
*
* *
* *
/ \
/ \
/ \
-------
/ \
/ \
/ \

bpbonline all rights reserved
Part I Functions 101
Function Library File Purpose: Example Argument(s) Result
cos(x) <math.h> Returns the cosine of angle x: double double
if x is 0.0 cos(x) is 1.0 (radians)
exp(x) <math.h> Returns e
x
where e = 2.71828 double double
fabs(x) <math.h> Returns the absolute value of its type double double
double argument:
if x is -8.432, fabs(x) is 8.432
floor(x) <math.h> Returns the largest whole number that is double double
not greater than x:
if x is 45.23, floor(x) is 45.0
log(x) <math.h> Returns the natural logarithm of x for x > double double
0.0:
if x is 2.71828, log(x) is 1.0
log
10
(x) <math.h> Returns the base 10 logarithm of x for x > double double
0.0:
pow(x,y) <math.h> Returns x
y
. If x is negative, y must be a double double
whole number: if x is 0.16 and y is 0.5,
pow(x,y) is 0.4
sin(x) <math.h> Returns the sine of angle x: if x is 1.5708, double double
sin(x) is 1.0 (radians)
sqrt(x) <math.h> Returns the non-negative square root of x double double
for
0.0:
if x is 2.25, sqrt(x) is 1.5
tan(x) <math.h> Returns the tangent of angle x: double double
if x is 0.0, tan(x) is 0.0 (radians)
Exa mp le 2
The program shown in Figure 5.8 uses the built in functions pow (power) and sqrt (square root) to
compute the roots of a quadratic equation in x:
The two roots are given by
The discriminant (disc) is defined as
When the value of the discriminant is greater or equal to zero, the roots of the quadratic equa-
tion exist, otherwise the roots are imaginary.
(x)
x
ax
2
+ bx + c = 0
root_1 =
b + (b
2
4ac)
(2a)
root_2 =
b (b
2
4ac)
(2a)
(b
2
4ac) .
bpbonline all rights reserved
102 Programming in C++ Part I
/* Computing the roots of a quadratic equation */
#include<iostream.h>
#include<stdio.h>
#include<math.h>
double disc,root_1,root_2;
double a,b,c;
main ()
{
cout << "\n Input the values of a, b and c :";
cin >> a >> b >> c;
disc = pow(b,2) - 4 * a * c;
if (disc >=0)
{root_1 = (-b + sqrt(disc))/(2*a);
root_2 = (-b -sqrt(disc))/(2*a);
cout << "\n Root1 = " << root_1 << endl;
cout << "\n Root2 = " << root_2 << endl;
}
else
{
cout << "\n No real root exists \n" ;
}
}
Figure 5.8 Program to calculate roots of a quadratic equation
5.1.4 User Defined Functions
Apart from the built in C++ library functions, users can also define their own functions to do a task
relevant to their programs. Such functions are called user-defined functions. These functions
should be codified by the user, so that such functions can perform the task as desired by the user.
Typ e s of Use r De fine d Func tions
The user defined functions may be classified in the following three types. Each type is based on
the formal arguments or parameters passed to the functions and the usage of return statement.
These types are:
(a) A function is invoked or called without passing any formal argument from the calling por-
tion of a program and also the function does not return any value to the called function.
(b) A function is invoked by the calling program and formal arguments are passed from the
calling program but the function does not return any values to the calling program.
(c) A function is invoked with formal arguments from the calling portion of a program which
returns value(s) to the calling program.
5.1.5 Advantages of Functions
The following are some advantages of using functions:
bpbonline all rights reserved
Part I Functions 103
(a) The complexity of the entire program can be divided into simple subtasks and function
subprograms can be written for each subtasks.
(b) The subprograms are easier to write, understand and debug.
(c) A function can be shared by other programs by compiling it separately and loading them
together.
(d) In C++, a function can call itself again. It is called recursiveness. Many calculations can
be done easily using recursive process such as calculation of factorial of a number.
(e) The functions such as cout, cin, the numerical computation functions sin, cos, sqrt etc.,
are used very frequently. Hence these are kept in C++ library and compiler is written in
such a way that any C++ program can call any of the library functions.
5.2 DEFINING A FUNCTION
A function definition has a name, a parentheses pair containing zero or more parameters and a
body. For each parameter, there should be a corresponding declaration that occurs before the body.
Any parameter not declared is taken to be an int by default. For good programming, one should
declare all parameters. Turbo C++ compiler permit including the argument declaration with the
parentheses.
The general format of the function definition is as follows:
func_type func_name(datatype argument1,
datatype argument2...)
{
body of the function
_______________
return statement;
}
5.2.1 Declaring the type of Function
The function refers to the type of value it would return to the calling portion of the program. Any
of the basic data types such as int, float, char etc. may appear in the function declaration. In case,
when a function is not supposed to return any value, it may be declared as type void. For example:
int func_name (int a );
void func_nam (float b);
5.2.2 Function Name
The function name can be any name conforming to the syntax rules of the variables. One should
normally use a function name relevant to the function operation. For example:
void show(void)
void square (int a, int b)
bpbonline all rights reserved
104 Programming in C++ Part I
Figure 5.9 illustrates the definition of a user defined line() function. You will notice that the
function definition is at the beginning of the function itself, and the semicolon is not used after the
name of the function. The program is shown in Figure 5.10.
Figure 5.9
Definition of
line() funciton
int j ;
for ( j = 1 ; j < 20 ; j ++ )
cout << " * " ;
cout " \ n " ;
Body of function
function name
defines function
note : no semicolon
Void
Line (void)
{
}
#include<iostream.h>
#include<stdio.h>
void line(void)
{
int j;
for (j = 1; j < 20; j++)
cout << "*";
cout << "\n";
}
main ()
{
line();
}
Figure 5.10 Program using line() function
The absence of semicolon enables the C++ compiler to know that you are defining a
function and not calling a function.
5.2.3 Formal Arguments
Any variable declared in the body of a function is said to be local to that function. Other variables
that are not declared within the body of the function are assumed to be global to the function and
bpbonline all rights reserved
Part I Functions 105
must be defined externally.
int counter (float x1, int x2, char c)
{
__________
return (int value);
}
In the above program segment, x1, x2 and c are formal arguments applicable to the function
only. The function returns an int value to the calling program.
The program listed in Figure 5.10 uses a line() function to draw a line containing 20 asterisks
(*). We can draw any number of such lines by calling the line() function. Thus there is no need to
write a program every time. You need to define the function once and call the user defined func-
tion any number of time to perform the desired function. The variable j used in line() function in
Figure 5.9 is only known to line(). It is invisible to the main() function. If we used this variable in
function main() without declaring it there, then compiler gives an error message because main()
would not know any thing about this variable. This is very important to know while writing func-
tions in C++. Variables used in a function are unknown outside the function. Thus a local variable
will be known to the function it is defined in, but not to others. A local variable used in this way in
a function is known in C++ as an "automatic" variable, because it is automatically created when a
function is called and destroyed when the function returns.
The following program demonstrates the function declaration, function calling and function
definition.
// Program demonstrating function calling, declaration and defi-
nition
#include<iostream.h>
void show (void); //prototype
void main (void)
{
void show (void); // function declaration
show(); // function calling
}
void show(void) // function definition
{
cout << "demonstration program \n";
cout << " for calling a function \n";
} /* end of function */
The output of the program will be:
demonstration program
for calling a function
bpbonline all rights reserved
106 Programming in C++ Part I
Exa mp le 3
The program given in Figure 5.11 uses a special character \x7 which is called BELL in the stan-
dard ASCII code. By using the cout statement, we can create a beeping sound by using this code.
The program calls a function called twobeep(). The function sounds two beeps separated by a short
silent interval. Then the program asks you to type a letter. When you do, it sounds the two beeps
again. You should note how the delay is created. A for loop is set up to cycle 1000 times. You will
notice that there is no statement in the body of for loop. The statement consists of only the semi-
colon. This constitutes a "null" statement: a statement with nothing in it. Its only role is to termi-
nate the for loop after cycling 1000 times. This may be thought as a for loop for introducing delay
in the loop.
#include<iostream.h>
#include<stdio.h>
/*twobeep */
/*beeps the speaker twice */
void twobeep (void)
{
int k;
cout << "\x7";
for (k = 1; k < 1000; k++);
cout << "\x7";
}
main ()
{
char x;
twobeep();
cout << "\nType any character ";
cin >> x ;
twobeep();
}
Figure 5.11 Program using Bell character
5.2.4 Function Prototype
The prototype tells the C++ compiler in advance about some characteristics of a function used in a
program. A function prototype takes the form:
type function_name(type argument-1,
argument-2,....);
It has three main components. These are:
(a) Function type
(b) Function name
(c) Arguments
bpbonline all rights reserved
Part I Functions 107
Func tion typ e
The function "type" is the type of the returned value. If the function does not return a value, the
type is defined as void.
Func tion na me
The function name is any legal identifier followed by the parentheses without any spaces in
between.
Arg ume nts
The arguments (or parameters) are given inside the parentheses, preceded by their types and sep-
arated by commas. If the function does not use any parameters, the word void is used inside the
parentheses. Here are some examples for prototypes of built-in functions.
int getchar(void);
double pow(double x,double y);
void exit(int x);
The first function int getchar (void); returns an integer value and does not take any
arguments. The second function double pow(double x, double y); takes two double
arguments (the value of x and the value of y) and returns a value of the type double. The third
function void exit (int x); returns no value but it accepts an argument x of the type inte-
ger.
Function prototype serves to notify the C++ compiler of the type and number of argu-
ments that a function will use. You may occasionally encounter functions written with an
old method of prototyping such as "int func()," or without any prototyping at all. The
programs written in this way are prone to errors and hard to debug. Prototyping helps the
compiler to detect errors if the function is improperly used.
Actually, the header files such as iostream.h and stdio.h contain the prototypes of the built-in
C++ functions. You may sometimes forget to include the proper header file in your program, but
you still have the program running and may get correct results. This is because if you do not
include the header file, the compiler will use the default type which is of the type int for any func-
tion.
5.2.5 Use of void ( )
If the function is of the type void, no return statement is used. Actually, the main() block of the
C++ program is a function, and because no type is specified, it is therefore considered of the type
int. Turbo C++ compiler gives a warning if you do not use the return statement at the end of the
main() block. You can avoid this warning by writing your main function as given below:
bpbonline all rights reserved
108 Programming in C++ Part I
main()
{
statement(s);
return(0);
}
This means that no returned value is expected from the main function. Another way to avoid
the warning message is to use the void type like this:
void main()
{
.....
}
You may also run across programs with the main function declared as:
void main(void);
5.3 ACCESSING A FUNCTION
A user defined function is invoked or called from the main program simply by using its name,
including the parentheses containing the parameters to be passed, if any, which follow the name.
The parentheses are mandatory so that the compiler knows you are referring to a function and not
a variable that you forgot to declare.
5.3.1 Invoking a Function without Passing Argument(s)
It is the simplest way of writing a user defined function because there is no formal argument
transfer between the calling statement of the program and a called program function. Program
shown in Figure 5.12(a) calls the function sample() without passing any argument. The function
sample() after execution transfers the control back to the function main(). The presence of void in
the function void sample (void) shows that no value is passed to the function.
/ * Program for calling function without passing values from main() */
#include<iostream.h>
void sample (void); /* prototype declaration of function sample */
void main (void)
{
cout << " \n I am calling function sample \n"<< endl;
sample();
}
void sample (void) /* function definition */
{
cout << "Thank you for calling me. " << "I am sample " << endl;
} /* end of function */
Figure 4.12(a) A function without passing arguments
bpbonline all rights reserved
Part I Functions 109
Figure 5.12(b)
Output of the
program
shown in Fig-
ure 5.12(a)
5.3.2 Passing Arguments to Function
Arguments are used to pass the values of variable to a function. The structure of a function passing
one argument is shown in Figure 5.13(a).
In the definition of function bar1() shown in Figure 5.13(a), int score within the parenthesis is
the formal argument. This shows that the main() will transfer the argument for score which has a
integer value. The keyword void before bar1 indicates that the function bar1() does not return any
value to the main() block.
Figure 5.13(a)
Structure of
function with
one argument
You will observe the following points while using the function call with arguments:
(a) In the main() program, shown in Figure 5.13(b), the argument or parameter we want to
pass to the function bar1(), is included in the parentheses i.e. () following "bar1" such as in
the function call bar1(7).
(b) We can also use the variable in place of the constant value 7 within the parentheses namely
bar1(int score). This ensures that the value included between parentheses in the main pro-
gram is assigned to the variable between parentheses in the function definition [See Figure
5.13(c)]

I am calling function sample

Thank you for calling me. I am sample

int j;
for (j=1;j<=score;j++)
cout<<("\xCD");
cout<<("\n");
{
}
void bar1(int score)
Function definition
Formal argument
Type declaration of formal
argument
Body of function
bpbonline all rights reserved
110 Programming in C++ Part I
Figure 5.13(b)
Passing a con-
stant value to a
function
7
main( )
{
bar1(7);
}
void bar1(int score)
}
{
The value of 7 is assigned
to the variable
score (the argument)
in the function
Calling program
Function
Figure 5.13(c)
Passing a value
to a function
using
variable as an
argument
(c) The declaration for the variable score takes place between the braces just after the name
bar1. For example:
void bar1(int score)
25
main( )
{
bar1(25);
}
void bar1(int score)
}
{
Whatever argument value bar1
has that is passed to the
variable score
in the function
Calling program
Function
void bar1(int score)
score is called the
"actual argument"
"formal argument"
score is called the
bpbonline all rights reserved
Part I Functions 111
The unique placement of the declarations for the argument variables serves to remind the
compiler and the programmer that these are special variables whose values are supplied by the
calling program. The use of variable used as argument is illustrated in Figure 5.13(c).
Let us now study the program shown in Figure 5.14(a). This program generates a bar graph of
names and bars representing the value assigned to the variable score. The output of the program is
shown in Figure 5.14(b).
/* Program using argument to pass data to a function */
#include<iostream.h>
#include<stdio.h>
void bar1(int score)
{
int j;
for (j = 1; j <= score; j++)
cout << "\xCD"; /* draw double-line character */
cout << "\n";
}
main ()
{
cout << "arun \t";
bar1(25);
cout << "chacha \t";
bar1(35);
cout << "rima \t";
bar1(5);
cout << "hamam \t";
bar1(10);
cout << "ram \t";
bar1(20);
}
Figure 5.14(a) Program showing passing argument to function bar1()
Figure 5.14(b)
Typical run of
the program
shown in
Figure 5.14(a)
The purpose of the function bar1() is to draw a horizontal line, made up of the double-line
graphics character "\xCD" on the screen. The program shown in Figure 5.14(a) generates function
bar1() that draws a bargraph for names. The bar length is represented by the argument value given
to the function bar1(). For each person, the main program prints the name and then calls the func-
tions bar1(), using as an argument the score value entered for the function bar1().
arun
chacha
rima
hamam
ram
bpbonline all rights reserved
112 Programming in C++ Part I
The definition of the function bar1 is given first. The main program calls this function several
times by passing the value of the argument score. For example, bar1(25) calls the function bar1
and passes the argument 25 as the value of the score. The function prints the double line character
"CD" 25 times and returns control to main(). Similarly, in the next line of the main program,
bar1(35) is executed. In this case, a value of 35 is passed as value of score and double line char-
acter "CD" is executed 35 times. After this, control is returned to main program. The output is
shown in Figure 5.14(b).
Stora g e of Va lue s whe n p a sse d a s Arg ume nts to a Func tion
The program given in Figure 5.15(a) transfers the value of x and y to the function swap1() and the
function swap1() receives them and stores them as separate variables xx and yy in a separate loca-
tion in the main memory. It then prints the values of xx and yy when asked to do so.
/* This program demonstrates passing arguments to a function */
#include<iostream.h>
#include<stdio.h>
void swap1(int xx, int yy)
{
cout << "First is " << xx << endl;
cout << "Second is " << yy << endl;
}
main ()
{
int x=1;
int y=7;
swap1(x,y);
}
Figure 5.15(a) Program showing passing arguments values to a function
But this value is printed by taking the values from the main memory assigned for the variables
xx and yy (See Figure 5.15(b). This process known as passing arguments by value results in a
waste of memory space.
Exa mp le 3
The program shown in Figure 5.16(a) passes the formal arguments to a function cube but the
function cube does not return any value to the caller. It is one way communication between a call-
ing program and the function block. The output of the program is shown in Figure 5.16(b).
Exa mp le 4
The program shown in Figure 5.17(a) finds a cube of its number using a function declaration with
the return statement.
bpbonline all rights reserved
Part I Functions 113
Figure 5.15(b)
Values dupli-
cated in Func-
tions main
memory
/* Program for calling function by passing formal arguments from
main() */
#include<iostream.h>
void cube (int, int); /* prototype declaration of function cube */
void main (void)
{
int x, y;
cout << "\n enter integer values for x and y \n" << endl;
cin >> x >> y;
cube(x,y); /* function call */
}
void cube (int x, int y) /* function definition */
{
x = x*x*x;
y = y*y*y ;
cout << "x cube = " << x << endl;
cout << "y cube = " << y << endl;
} /* end of function */
Figure 5.16(a) Program showing passing formal argument to a function cube
7
1
main()
{
int x=1;
int y=7;
swap1(x,y);
}
x
y
{
void swap1(int xx,int yy)
}
1
7
xx
yy
Values are passed to function
and duplicated in the functions;
memory space.
bpbonline all rights reserved
114 Programming in C++ Part I
Figure 5.16(b)
Output of the
program
shown in Fig-
ure 5.16(a)
/* Program showing passing of formal arguments to function from
main() */
/* and computed value passed back to calling program */
#include <iostream.h>
float cube (float); /* prototype declaration of function cube */
void main (void)
{
float i,max,value;
max = 2.0;
i = -2.0;
while ( i <= max)
{
value = cube(i);
cout << "i = " <<"\t"<<i<<"\t"<<"i cube = " <<"\t"<<value<<
endl;
i = i + 0.5;
}
}
float cube (float n) /* function definition */
{
float value;
value = n*n*n;
return (value);
} /* end of function */
Figure 5.17(a) Program to find the cube of a given number using a function declaration with the return
statement
The output of the program is shown in Figure 5.17(b). In this program, the function cube() gets
the value of the parameter n. It calculates the cube of n and assigns it to value.
The statement return(value) transfers the calculated cube value of n to the main(). Thus, every
time the function cube(i) is called in the main() block, the calculated value of cube of the argument
is returned to the main(). The main() block uses a while loop to assign different values to the vari-
able i. This argument, i is transferred to the function float cube(float n).

enter integer values for x and y

4 5
x cube = 64
y cube = 125

bpbonline all rights reserved
Part I Functions 115
Figure 5.17(b)
output of the
program
shown in Fig-
ure 5.17(a)
5.3.3 Passing Multiple Arguments to a Function
You can pass as many arguments to a function as you wish. For example, in the program given in
Figure 5.18(a), two arguments are passed to a function called rectang1(). The purpose of this
function is to draw a rectangle whose sides are given as multiple arguments namely (int length, int
width) in the declaration:
void rectang1(int length,int width);
/* Program passing multiple arguments to a function */
#include<iostream.h>
#include<stdio.h>
void rectang1(int length, int width)
{
int j,k;
length /= 2; /* scaling length to half */
width /= 4; /* scaling width to one fourth */
for (j = 1; j <= width; j++)
{
cout << "\t\t" ;
for (k = 1; k <= length; k++) /* line of rectangles */
cout << "\xDB"; /* print one rectangle */
cout << "\n"; /* next line */
}
}
main ()
{
cout << "drawing room " << endl;
rectang1(22,12); /* draws shape of drawing room */
cout << "kitchen" << endl;
rectang1(10,7); /* draws shape of kitchen */
cout << "bedroom" << endl;
rectang1(12,12); /* draws shape of bedroom */
cout << "bathroom" << endl;
rectang1(6,8); /* draws shape of bathroom */
}
Figure 5.18(a) Passing multiple arguments to a function rectang1()
i = -2 i cube = -8
i = -1.5 i cube = -3.375
i = -1 i cube = -1
i = -0.5 i cube = -0.125
i = 0 i cube = 0
i = 0.5 i cube = 0.125
i = 1 i cube = 1
i = 1.5 i cube = 3.375
i = 2 i cube = 8
bpbonline all rights reserved
116 Programming in C++ Part I
The typical run of the program is shown in Figure 5.18(b). Figure 5.18(c) illustrates the pass-
ing of multiple arguments to a function.
Figure 5.18(b)
Typical run of
the program
shown in
Figure 5.18(a)
drawing room



kitchen

bedroom



bathroom



Figure 5.18(c)
Illustration of
passing multi-
ple arguments
to a function
void rectang1(int length,int width)
}
{
Function
void rectang1(int length,int width)
}
main()
Calling program
{
rectang1(22,12);
12
22
The first actual argument is passed
to the first formal argument; the
second actual argument is passed
to the second formal argument.
bpbonline all rights reserved
Part I Functions 117
5.3.4 Returning values by the Function
How function returns a value can be understood by the following analogy. Suppose you hire
someone to find out some information for you. Say for example, you dial telephone number. 174
to find out what time it is. You make the call, and the person (or computer) at the other end of the
line gives you the time. You do not need to tell them what you want which is understood when you
call that telephone number. No information flows from you to the telephone exchange but some
information is given back from it to you.
A function that accepts no arguments from the main() block, but returns a value performs a
similar role. You call the function, it gets a certain piece of information and returns it to you. The
built-in function getche() operates just in this way. You call it without giving it any
information and it returns the value of the first character typed on the keyboard.
Exa mp le 5
Suppose we want to build a function that returns a character but that also automatically translates
any uppercase characters into lower case. That means if we type A it returns a. This function is
given the name getlc() and the program is given in Figure 5.19(a).
#include<iostream.h>
#include<stdio.h>
/* getlc() */
/* returns character */
/* converts to lowercase if in uppercase */
char getlc(char)
{
char ch;
cin >> ch; /* read character */
if ( ch > 64 && ch < 91 ) /* if uppercase, */
ch += 32; /* add 32 to convert to lower case */
return (ch); /* return character value */
}
int main (void)
{
char chlc,ch;
cout << "\n Type a for first selection, b for second: ";
chlc = getlc(ch); /* get character */
switch (chlc) /* use it for switch */
{
case a:
cout << "\n you typed an a.";
break;
(Contd...)
bpbonline all rights reserved
118 Programming in C++ Part I
case b:
cout << "\n you typed b.";
break;
default:
cout << "\n you typed a nonexistent selection. ";
}
}
Figure 5.19(a) Program to convert character to lower case if in upper case
This new function, getlc() (for "get lowercase"), is called from the main program with the
statement:
chlc = getlc(ch);
This function can be used as if it were a variable in an assignment statement, and the value
returned (a lower case character) will be assigned to the variable chlc, which is then used in the
switch statement to determine which message will be printed. The output of the program is shown
in Figure 5.19(b). Note that the capital A typed by the user is converted to lowercase a.
Figure 5.19(b)
Output of the
program in
Figure 5.19(a)
The re turn Sta te me nt
Program given in Example 5, the function returned value to the calling program when it encoun-
tered the final closing brace (}) defined at the end of function.
No separate "return" statement was necessary. In the case of the program whose execution is
shown in Example 5, we want to return the value of the character read from the keyboard. In fact
we want to return one of the two possible values: the character itself, if it is in lowercase already,
or a modified version of the character, if it is in uppercase. So we use the if statement to check if ch
is in uppercase (uppercase letters run from ASCII 65 to 90). If so, we add 32 (the difference
between any upper and lower case character in ASCII (namely A = 65 and a = 97) to ch.
Finally, we return to the calling program with the new value of the character, by placing the vari-
able name between the parentheses following return().

Type a for first selection, b for second: A

you typed an a.
Type a for first selection, b for second: B

you typed b.
Type a for first selection, b for second: c

you typed a nonexistent selection.

bpbonline all rights reserved
Part I Functions 119
Purp ose of re turn( ) Sta te me nt:
The return() statement has two purposes.
(a) Transferring control from the function back to the calling program.
(b) Whatever is inside the parentheses following return is returned as a value to the calling pro-
gram.
Figure 5.20 shows a function returning a value to the calling program. The return statement need
not be at the end of the function. It can be placed anywhere in the function; as soon as it is
encountered, control will return to the calling program. For example, the function getlc() written in
Example 5 could be rewritten as shown in Figure 5.21.
Figure 5.20
Function
Returning a
Value to the
calling pro-
gram
#include<iostream.h>
#include<stdio.h>
/* getlc() */
/* returns character */
/* converts to lowercase if in uppercase */
char getlc(ch)
{
char ch;
cin >> ch; /* read character */
(Contd...)
main ( )
{
}
ans = func ( ) ;
}
{
x = 3 ;
func ( )
return (x) ;
Calling program Function
The value of x ,
which is 3 , is
returned to
and assigned to
main ( )
ans.
3
bpbonline all rights reserved
120 Programming in C++ Part I
if ( ch > 64 && ch < 91 ) /* if uppercase, */
return (ch+32); /* return converted value */
else /* otherwise */
return (ch); /* return character value */
}
Figure 5.21 Alternative form of program to convert a character to lower case if in upper case
In this modified version of the program, different return statements are used depending on
whether ch is uppercase or not.
The return statement can also be used without parentheses. When this is the case, no value
is returned to the calling program.
Limita tion of re turn( ) Sta te me nt:
Main limitation in the use of the return() statement is that you can only use it to return one value.
Exa mp le 6
The program shown in Figure 5.21(a) uses the function factorial to calculate the factorial of a
number between 0 and 10.
/* Computes and prints the factorial of a number */
/* Demonstrates an user-defined function that has an input
parameter */
#include<iostream.h>
#include<stdio.h>
/* function computes factorial n */
int factorial(int n)
{
int i,product; /* local variable */
product = 1;
/* Computes the product n into (n-1) (n-2) ... 2 1 */
for ( i = n; i > 1; i = i - 1)
{
product = product * i;
}
/* Returns function result */
return (product);
}
(Contd...)
bpbonline all rights reserved
Part I Functions 121
void
main (void)
{
int num, fact;
cout << "\n Enter an integer between 0 and 10: ";
cin >> num;
if (num < 0)
{
cout << "\n The factorial of a negative number is
undefined" << num;
}
else
if (num <= 10)
{
fact = factorial(num);
cout << "\n The factorial of " << num << " is " << fact;
}
else
{
cout << "\n Number out of range " << num;
}
}
Figure 5.21(a) Program for calculating factorial of a number
You will observe that if the input value stored in the variable num of function main is between 0
and 10, the statement:
fact = factorial(num);
is executed. The output of the program is shown in Figure 5.22(b).
When the function factorial is referenced then the function is executed, and the assignment
statement:
fact = factorial(num);
in the main() gets the result of the calculations carried out in the function dfactorial().
Figure 5.22(c) shows how the value of num, the actual argument in the function call, is used as
the formal parameter n at the time when function factorial is executed. The result of the execution
of factorial is returned to the main function, assigned to the variable fact, and displayed.
Exa mp le 7
The program shown in Figure 5.23(a), transfers the three values from the main() block to the
function largest(). The function returns the largest of the three back to the main program
using multiple if statements. The output is shown in Figure 5.23(b)
bpbonline all rights reserved
122 Programming in C++ Part I
Figure 5.22(b)
Output of the
program in
Figure 5.22(a)
Enter an integer between 0 and 10: 0

The factorial of 0 is 1
Enter an integer between 0 and 10: 4

The factorial of 4 is 24
Enter an integer between 0 and 10: 10

The factorial of 10 is 24320
Enter an integer between 0 and 10: -5

The factorial of a negative number is undefined-5
Enter an integer between 0 and 10: 11

Number out of range 11
Figure 5.22(c)
Effect of execu-
tion of factorial
when num is 5 /*
* Computes Factorial n
* Pre: n is greater than or equal to zero */
int
factorial(int n)
{
int i, /* local variables */
product = 1;
/* Compute the product n x (n - 1) x (n - 2)
x ... x 2 x 1 */
for (i = n; i > 1; i = i - 1) {
product = product * i;
}
/* Return function result */
return (product);
}
Call factorial with n = 5
Return result value of 120
fact = factorial (num);
bpbonline all rights reserved
Part I Functions 123
/* Program using function to find largest of three numbers */
#include<iostream.h>
float largest (float, float, float);
void main (void)
{
float u,v,w,max;
cout << "\n Enter any three numbers \n";
cin >> u >> v >> w;
max = largest(u,v,w);
cout << "largest of the three numbers = " << max;
}
float largest (float x, float y, float z)
{
if ( x > y )
{
if ( x > z )
return (x);
else return (z);
}
else
{
if ( y > z )
return (y);
else
return (z);
}
} /* end of function */
Figure 5.23(a) Program using a function for calculating the largest of three numbers
Figure 5.23(b)
Output of the
program in
Figure 5.23(a)
5.3.5 Organization of Program containing Functions
Organize your program according to the following steps:
(a) Begin with a block comment identifying the programs purpose.
(b) Include any preprocessor directives such as
#define, etc.

Enter any three numbers
4.01 3.201 4.001
largest of the three numbers = 4.01

bpbonline all rights reserved
124 Programming in C++ Part I
(c) Precode definitions of your function subprograms before any call to them
5.4 PASSING ADDRESSES TO A FUNCTION
In sections 5.3.1 and 5.3.2, we have seen how to pass value(s) to a function. In some cases the
function also returns a single value to the main program. But how can a function return more than
one value to the calling program? This is achieved by passing the value of the argument by refer-
ence or passing the address where the argument is stored in the main memory. This is better
understood by the concept of pointers.
In order to economize on the main memory and to transfer multiple values from the function
to the main() or the calling program, we use pointers. The calling program, instead of passing val-
ues of arguments to the function, passes their addresses. These addresses are where the calling
program wants the function to place the data it modifies. This is explained in Chapter 6 of Part II.
TEST PAPER
Time: 3 Hrs
Max Marks: 100
Answer the following questions.
1. Which of these are valid reasons for using functions?
(a) They use less memory than repeating the same code.
(b) They run faster.
(c) They keep different program activities
separate.
(d) They keep variables safe from other parts of the program.
Ans [All except (b) are valid reasons for using functions]
2. Which of the following are valid reasons for using arguments in functions?
(a) To tell the function where to locate itself in memory.
(b) To convey information to the function that it can operate on.
(c) To return information from the function to the calling program.
(d) To specify the type of the function.
Ans (b and c)
3. Which of the following can be passed to a function via arguments?
(a) constants
(b) variables (with values)
(c) preprocessor directives
(d) expressions (that evaluate to a value)
bpbonline all rights reserved
Part I Functions 125
(e) functions (that return value)
Ans (a, b d and e)
4. Write a program in C++ that prints out the larger of two numbers entered from the key-
board. Use a function to do the actual comparison of the two numbers. Pass the two
numbers to the function as arguments, and have the function return the answer.
5. Write a program in C++ that asks the user to input length of the two sides of a right
angled triangle. Make use of the built-in functions pow and sqrt functions to compute the
length of the hypotenuse using the Pythagorean theorem.
6. When do you use the keyword return while defining a function? When do you not use
the keyword return when defining a function?
7. Write a C++ program that asks for a distance in meters and converts it into feet.
8. Write a program in C++ to call a function which returns the cube of a given number.
9. Write a program to accept a binary number and convert it into a decimal number.
bpbonline all rights reserved

S-ar putea să vă placă și