Chapter 4 FUNCTIONS

In addition to function main, a program source module may contain one or more other functions.

The execution of the program always starts with function main.

The statements of another function are executed only if that function is called in function main or in any other function that is called in function main.

After the statements in a function are executed, the next statement to be executed is the one that follows the statement in which that function is called.

Example

  • Two versions of a program to compute the area and the perimeter of two rectangles are provided in figure 4.1.a and figure 4.1.b respectively.
  • The program in figure 4.1.a computes the area and the perimeter of both rectangles in the body of function main.
  • Whereas the program in figure 4.1.b does it by calling function computeAreaPeri.
  • The statements of the program in figure 4.1.b are executed in the following order: 23, 24, 26, 15, 16, 27, 28, 31, 32, 34, 15, 16, 35, 36, and 37.

Figure 4.1.a

  1. /*----- Program to compute the area and the perimeter of rectangles ------*/
  2. #include <iostream>
  3. using namespace std;
  4. int main ()
  5. {
  6. double len, // to hold the length of the rectangle
  7. Width, // to hold the width of the rectangle
  8. area, // to hold the area
  9. peri; // to hold the perimeter
  10. /*------compute and print the area and the perimeter of a rectangle with length 45 and width 34 ------*/
  11. len = 45;
  12. width = 34;
  13. area = len * width;
  14. peri = 2 * ( len + width );
  15. coutendl“the area of the rectangle is:\t”area;
  16. coutendl“Its perimeter is:\t” peri;
  17. /*------read the length and the width of a rectangle and compute and print its area and perimeter ------*/
  18. coutendl“enter the length and the width of the rectangle:\t”;
  19. cinlenwidth;
  20. area = len * width;
  21. peri = 2 * ( len + width );
  22. coutendl“the area of the rectangle is:\t” area;
  23. coutendl“Its perimeter is:\t” peri;
  24. return ( 0 );

}

Figure 4.1.bDefining and Calling a void Function without Parameters

  1. /*----- Program to compute the area and the perimeter of rectangles ------*/
  2. #include <iostream>
  3. using namespace std;
  4. double len,// to hold the length of the rectangle
  5. width,// to hold the width of the rectangle
  6. area,// to hold the area
  7. peri;// to hold the perimeter
  8. /*------function computeAreaPeri ------*/
  9. /*------compute the area and the perimeter of the rectable ------*/
  10. void computeAreaPeri( void )
  11. {
  12. area = len * width;
  13. peri = 2 * ( len + width );
  14. }
  15. int main ()
  16. {
  17. /*------compute and print the area and the perimeter of a rectangle with length 45 and width 34 ------*/
  18. len = 45;
  19. width = 34;
  20. computeAreaPeri( );
  21. coutendl“the area of the rectangle is:\t” area;
  22. coutendl“Its perimeter is:\t” peri;
  23. /*------read the length and the width of a rectangle and compute and print its area and perimeter ------*/
  24. coutendl“enter the length and the width of the rectangle:\t”;
  25. cinlenwidth;
  26. computeAreaPeri( );
  27. coutendl“the area of the rectangle is:\t” area;
  28. coutendl“Its perimeter is:\t” peri;
  29. return ( 0 );

}

  • Notice the following two facts in the programs in figures 4.1.a and 4.1.b:
  • The body of function computeAreaPeri (lines 15-16) is written inside the body of function main in figure 4.1.a twice, starting at the locations where it is called in the body of function main in figure 4.1.b: lines 19-20, and lines 29-30.
  • Variables len, width, area, and peri are defined in the body of function main in figure 4.1.a; but they are defined outside of the bodies of function main and computeAreaPeri in the program in figure 4.1.b.

Variables that are defined in the body of a function are the local variables of that function and variables that are defined outside of the body of a function are called global variables.

Types of Function in C++

There are two types of functions in the C++ programming language:

  • Functions that do not return a value:voidfunctions, and
  • Functions that return a value.

Defining and Calling a void Function

Avoid function may or may not have parameters.

You define a void function without parameters as follows:

void <function-name>( )

{

<Body-of-the-function>

}

<function-name>is the name of the function

void <function-name>( )is the function header.

It may also be specified as follows:void <function-name>( void )

<Body-of-the-function>is the body of the function:It consists of one or more statements that are executed each time the function is called.

©2010 Gilbert NdjatouPage 1

You call a void function without parameters as follows:

<function-name> ( );

The programs in figure 4.1.b and figure 4.2 illustrate the definition of void functions without parameters, and calls of those functions.

Global Variables and Local Variables

As stated above, Variables that are defined in the body of a function are the local variables of that function and variables that are defined outside of the body of a function are called global variables.

Examples of Global Variables

  • In the source module in figure 4.1.b, variableslen, width, area, and peri are defined in lines 6 to 9 which are outside of the bodies of the functions main and computeAreaPeri.
  • In the source module in figure 4.2, variables MaxCount and AvgScore are defined in lines 7 and 8 respectively, which are outside of the bodies of the functions main and process_score.

Examples of Local Variables

  • In the source module in figure 4.2,

score, totalScore, and count are the local variables of function process_scores.

qAvgScore, and tAvgScore are the local variables of function main.

A global variable can be accessed in the body of any function that appears after its definition.

But a local variable can be accessed only in the body of the function in which it is defined.

Example

In the source module in figure 4.2,

score, totalScore, and count cannot be accessed in function main.

qAvgScore, and tAvgScore cannot be accessed in function process_scores.

Global variables are in general used to pass information from one function to another in a source module.

Example

In the source module in figure 4.1.b:

  • Function main stores 45 into global variable len in line 23, and 34 into global variable width in line 24 before it calls function computeAreaPeri in line 26.
  • In line 15, function computeAreaPeri retrieves 45 from variable len and 34 from variable width, multiplies 45 by 34, and stores the result, 1530.0 in global variable area.
  • In line 16, function computeAreaPeri retrieves 45 from variable len and 34 from variable width, computes 2 * (45 + 34), and stores the result, 158.0 in global variable peri.
  • In line 27, function main retrieves 1530.0 from global variablearea and prints it.
  • In line 28, function main retrieves 158.0 from global variable periand prints it.

Figure 4.2Defining and Calling a void function without Parameters

Line Number

1/****************************************************************

2Program to compute the weighted average score of a student who has completed 8 quizzes and 5 tests. The function process_score is used to read the quizzes scores and to compute their average. It is also used to read the tests scores and to compute their average.

3****************************************************************/

4#include <iostream>

5using namespace std;

6

7int maxCount;// the number of quiz or test scores

8double avgScore;// the average quiz or test score

9

10/* ------definition of the function process_scores () ------*/

11/* read scores and compute their average */

12void process_scores ( )

13{

14double score,//a student’s test or quiz score

15totalScore;//a student’s total test or quiz score

16int count;//to count a student’s test or quiz scores

17totalScore = 0;

18count = 0;

19

20/*------read scores and compute their total ------*/

21while (count < maxCount )

22{

23cin >score;

24totalScore = totalScore + score;

25count = count + 1;

26}

27

28/*------compute the average score ------*/

29avgScore = totalScore / maxCount;

30}

31

32int main( )

33{

34doubleqAvgScore,//a student’s average quiz score

35tAvgScore;//a student’s average test score

36

37/* read the student’s quiz scores and compute their average */

38coutendl“enter all quiz scores for the student:\t”;

39maxCount = 8;

40process_scores ( );

41qAvgScore = avgScore;

42

43/*-read the student’s test scores and compute their average */

44coutendl“enter all test scores for the student:\t”;

45maxCount = 5;

46process_scores ( );

47tAvgScore = avgScore;

48

49/*------compute and print the student’s average score ----*/

50coutendl“the average score is:\t”

51(.3 * qAvgScore + .7 * tAvgScore );

52return 0;

53}

Exercise 4.1*

Execute the following program and show its output for the input value 7:

#include <iostream>

using namespace std;

int gnum1, gnum2;

void funct(void)

{

int num = gnum1 + 10;

gnum1 = gnum1 +num;

gnum2 = 2 * gnum1 + 5;

}

int main( )

{

gnum1 = 15;

funct( );

cout < endl < “gnum1=” < gnum1 < “\tgnum2=” < gnum2;

cin > gnum1;

funct( );

cout < endl < “gnum1=” < gnum1 < “\tgnum2=” < gnum2;

return 0;

}

Exercise 4.2*

Write a void function without parameters computeAreaPeri that computes the area and the perimeter of a circle which are output in function main.

  1. Function main first calls function computeAreaPeri to compute the area and the perimeter of the circle with radius 5.43.
  2. It then reads the radius of a circle and then calls function computeAreaPeri againto compute the area and the perimeter of this circle.

You must first determine and define the global variables of this program; then write function computeAreaPeri, and finally write function main.

Exercise 4.3

Execute the following program and show its output for the input value 15:

#include <iostream>

using namespace std;

int gnum1, gnum2;

void funct(void)

{

int num = 2 * gnum1 + 5;

gnum2 = gnum1 + num;

gnum1 = gnum2 + 10;

}

int main( )

{

gnum1 = 25;

funct( );

cout < endl < “gnum1=” < gnum1 < “\tgnum2=” < gnum2;

cin > gnum1;

funct( );

cout < endl < “gnum1=” < gnum1 < “\tgnum2=” < gnum2;

return 0;

}

Exercise 4.4

Write a void function without parameters computeTaxNet that uses the gross pay of an individual to compute his tax deduction and net pay that are printed in function main. The tax deduction is computed as follows: if the gross pay is greater than or equal to $1000.00, then the tax deduction is 25% of the gross pay; otherwise, it is 18% of the gross pay. The net pay is the gross pay minus the tax deduction.

  1. Function main first callsfunction computeTaxNet to compute the tax deduction and the net pay for the gross pay $1250.
  2. It then reads the gross pay of an individual and then callsfunction computeTaxNet to compute his tax deduction and net pay.
  3. You must first determine and define the global variables of this program; then write function computeTaxNet, and finally write function main.

Basic Properties of Functions

  1. DefinitionA function is defined only once by writing its function header followed by its constituent statements enclosed between the left brace { and the right brace }.
  1. ExecutionAt any point in another function where the effect of a function is needed, use a call statement to pass the control of the execution of a program to that function. After the execution of the last statement in the body of a function, the control of the execution of the program returns to the statement that follows the call statement.
  1. PlacementA function may be called in a source module only if it has been written (defined) or declaredbefore the call statement.

Example

In the source module in figure 4.1.b function computeAreaPeri is written before function main, and in the source module in figure 4.2 function process_scoresis written before function main.

Function Prototypes

You declare a function by writing its function header followed by the semicolon. This statement is called function prototype.

Example

The function prototype of function computeAreaPeri in figure 4.1b is:

void computeAreaPeri( );orvoid computeAreaPeri( void );

The function prototype of functionprocess_scores4.2 is:

void process_scores( );orvoid process_scores( void );

When you write a source module, it is a good programming practice to first write the function prototypes of all the functions called in the source module followed by function main, and then all other functions as in the source module in figure 4.3.

Figure 4.3Using function Prototypes

  1. /*----- Program to compute the area and the perimeter of rectangles ------*/
  2. #include <iostream>
  3. using namespace std;
  4. void computeAreaPeri( );//to compute the area and perimeter of a rectangle
  5. double len,// to hold the length of the rectangle
  6. width// to hold the width of the rectangle
  7. area,// to hold the area
  8. peri;// to hold the perimeter
  9. int main ()
  10. {
  11. /*------compute and print the area and the perimeter of a rectangle with length 45 and width 34 ------*/
  12. len = 45;
  13. width = 34;
  14. computeAreaPeri( );
  15. coutendl“the area of the rectangle is:\t” area;
  16. coutendl“Its perimeter is:\t” peri;
  17. /*------read the length and the width of a rectangle and compute and print its area and perimeter ------*/
  18. coutendl“enter the length and the width of the rectangle:\t”;
  19. cinlenwidth;
  20. computeAreaPeri( );
  21. coutendl“the area of the rectangle is:\t” area;
  22. coutendl“Its perimeter is:\t” peri;
  23. return ( 0 );
  24. }
  25. /*------function computeAreaPeri ------*/
  26. /*------compute the area and the perimeter of the rectangle------*/
  27. void computeAreaPeri( )
  28. {
  29. area = len * width;
  30. peri = 2 * ( len + width );
  31. }

Exercise 4.5*

Correct the mistake(s) in each of the following source modules.

(a)

#include <iostream>

using namespace std;

int num1, num2, result;

int main( )

{

num1 = 5;

num2 = 17;

getanswer1( );

cout < endl< “The result of the compuation is:\t” < result;

return ( 0 );

}

void getanswer1(void)

{

result = 4 * num1 - 3 * num2;

}

(b)

#include <iostream>

using namespace std;

int num1, num2, result;

void getanswer2(void)

{

result = num1 / 4 + num2 % 5;

}

int main( )

{

num1 = 5;

num2 = 17;

getanswer2(void);

cout < endl< “The result of the compuation is:\t” < result;

return ( 0 );

}

Exercise 4.6*

Rewrite the source module of exercise 4.1 by first writing function main before function funct.

Exercise 4.7

Rewrite the source module of exercise 4.3 by first writing function main before function funct.

Writing a voidFunction with Parameters

You write a voidfunction with parameters by specifying the parameters and their data types in the parentheses that follow the function name in the function header as follows:

void <function-name>( type1 parameter1, type2 parameter2, type3 parameter3, . . . )

{

<Body-of-the-function>

}

There are two types of parameters in C++: value parameters and reference parameters.

You distinguish a value parameter from a reference parameter by placing the ampersand character, in front of reference parameters.

Example

void computeAreaPeri2( double len, double wid, double &ar, double &peri )

{

ar = len * wid;

peri = 2 * ( len + wid );

}

  • len and wid are value parameters.
  • ar and peri are reference parameters.

Parameters are used in the body of a function in the same way that its local variables are used.

Calling a voidFunction with Parameters

You call of avoid function with parameters by using a statement consisting of the function name followed by the arguments between the parentheses as follows:

  • For each value parameter, the argument must be a value or an expression.
  • For each reference parameter, the argument must be a variable name.
  • You must also specify an argument for each parameter.
  • The data type of an argument must be compatible with the data type of the corresponding parameter.

Examples

Given the following function:

void computeAreaPeri2( double len, double wid, double &ar, double &peri )

{

ar = len * wid;

peri = 2 * ( len + wid );

}

And given the following definitions of variables in function main:

double length = 25.00, width = 10.00,

area, perimeter;

The following calls of the function computeAreaPeri2 are valid:

  1. computeAreaPeri2( 27.42, 16.25, area, perimeter );
  2. computeAreaPeri2( length, width, area, perimeter );
  3. computeAreaPeri2( length + 5.0, 8.50, area, perimeter );
  4. computeAreaPeri2( length, width * 2, area, perimeter );

The following calls of the function computeAreaPeri2 are invalid:

  1. computeAreaPeri2( 27.42, 16.25, 50.5, perimeter );

the argument that corresponds to the reference parameter ar is 50.5 which is not a variable name.

  1. computeAreaPeri2( length, width, area, perimeter + 4);

the argument that corresponds to the reference parameter peri is perimeter + 5 which is not a variable name.

  1. computeAreaPeri2( 8.50, area, perimeter );

only 3 arguments (instead of 4) are provided.

Exercise 4.8*

Assume given the following definition of function process:

void process(int vnum, int & rnum1, int & rnum2)

{

vnum = vnum + 5;

rnum1 = rnum1 + 10;

rnum2 = vnum + rnum1;

}

And that local variables are defined in function main as follows:

int num1 = 6, num2 = 9, num3 = 12;

Indicate whether each of the following calls of function process is valid or invalid. Also give the reason why a call is invalid.

  1. process( 15, num2, num3 );
  2. process( 21, num1 + 3, num2 );
  3. process( num3, num1, num2 );
  4. process( num1, 10, num3 );
  5. process( 3, num1, 25 );
  6. process( num1, num2, num3 + 4);
  7. process( num2, num1 );
  8. process( num1 + 3, num2, num3);
  9. process( 5, num3 );
  10. process( num1, num1, num3 );

Processing Arguments/Parameters in the Body of a Function

The following actions take place when a function with parameters is called:

  • A memory location is created for each value parameter and the value of the corresponding argument is stored into it.
  • Each reference parameter is replaced in the body of the function with the corresponding argument.

Example

Given the following definition of function computeAreaPeri2( ):

void computeAreaPeri2( double len, double wid, double &ar, double &peri )

{

ar = len * wid;

peri = 2 * ( len + wid );

}

Assume that local variables are defined in function main as follows:

double length = 25.00, width = 10.00,

area, perimeter;

  1. After the call statement:computeAreaPeri2( 80.00, 50.00, area, perimeter );

The body of function computeAreaPeri2 is executed as if it was written as follows:

{

len = 80.00;

wid = 50.00;

area = len * wid;

perimeter = 2 * ( len + wid );

}

After the execution of function computeAreaPeri2, local variables area and perimeter of function main will have the following values:

area:4000.00, perimeter:260.00

  1. After the call statement:computeAreaPeri2( length + 5, width, area, perimeter );

The body of function computeAreaPeri2 is executed as if it was written as follows:

{

len = 30.00;

wid = 10.00;

area = len * wid;

perimeter = 2 * ( len + wid );

}

After the execution of function computeAreaPeri2, local variables area and perimeter of function main will have the following values:

area:300.00, perimeter:80.00

Exercise 4.9*

Assume given the following definition of function process:

void process(int vnum, int &first, int & second)

{

vnum = vnum + second;

first = first + 10;

second = vnum + first;

}

And that local variables are defined in function main as follows:

int num1 = 6, num2 = 9, num3 = 12;

For each of the following calls of function process, show the body of function process in the way it is executed after the call, then execute function process and display the corresponding output.

  1. process( 15, num2, num3 );

cout < endl < “num1=” < num1 < “num2=” < num2 < “num3=” < num3;

  1. process( num1, num2, num3 );

cout < endl < “num1=” < num1 < “num2=” < num2 < “num3=” < num3;

  1. process( num1 + 3, num2, num3);

cout < endl < “num1=” < num1 < “num2=” < num2 < “num3=” < num3;

Exercise 4.10

Assume given the following definition of function process:

void process(int vnum, int & first, int & second)

{

vnum = vnum * second;

first = first + 10;

second = vnum - first;

}

And that local variables are defined in function main as follows:

int num1 = 6, num2 = 9, num3 = 12;

Indicate whether each of the following calls of function process is valid or invalid. Also give the reason why a call is invalid. For each valid call, show the body of the function in the way it is executed after the function call, then execute the function and show the contents of the variables num1, num2, and num3 after the function is executed. Assume that the function calls are independent of each other.

  1. process( num1, num2, num3 );
  2. process( num3, num1, num2 );
  3. process( num1, 10, num3 );
  4. process( 3, num1, num2 );
  5. process( num1, num2, num3 + 4);
  6. process( num1 + 3, num2, num3);
  7. process( 5, num3 );
  8. process( num1, num1, num3 );

Function Prototype of a void Function with Parameters

As with void functions without parameters, the function prototype of a void function with parameters is a statement that consists of its function header.