FUNCTIONS

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

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

Defining and Calling a void Function

Syntax of a void Function without Parameters

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.

You call a void function without parameters as follows:

<function-name> ( );

Case Study 1

Problem

In a high school math class, each student has completed 8 quizzes and 5 tests, and has received a score in the range of 0 to 100 in each of those quizzes and tests.

The math teacher wants you to write a program that he or she will use to compute a student’s average score for the marking period as follows:

1.Read and compute the total score of all quizzes.

2.Compute the average score of the quizzes.

3.Read and compute the total score of all tests

4.Compute the average score of the tests.

5.Compute the average score for the marking period as follows:

0.3 x (average quiz score) + 0.7 x (average test score)

This program is written in such a way that the section of the code that reads the quiz/test scores and computes their average is specified in the body of a function that is called in function main:

Figure 1Defining and Calling a void function without Parameters

Line Number

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

2Program to compute a student’s average score in a marking period

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

4#include <iostream>

5using namespace std;

6int MaxCount;// the number of quiz or test scores

7double AvgScore;// the average quiz or test score

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

9/* read scores and compute their average */

10void process_scores ( )

11{

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

13TotalScore;//a student’s total test or quiz score

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

15TotalScore = 0;

16count = 0;

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

18while (count < MaxCount )

19{

20cin >score;

21TotalScore = TotalScore + score;

22count = count + 1;

23}

24/*------compute the average score ------*/

25AvgScore = TotalScore / MaxCount;

26}

27

28int main( )

29{

30doubleQAvgScore,//a student’s average quiz score

31TAvgScore;//a student’s average test score

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

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

34MaxCount = 8;

35process_scores ( );

36QAvgScore = AvgScore;

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

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

39MaxCount = 5;

40process_scores ( );

41TAvgScore = AvgScore;

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

43coutendl“the average score is:\t”

44(.3 * QAvgScore + .7 * TAvgScore );

45return 0;

46}

Global Variables and Local Variables

Two variables, MaxCount and AvgScore are defined outside of the body of function main and function process_scores.

Variables that are defined outside of the body of any function are called Global variables.

Variables defined in the body of a function are called local variables.

score, TotalScore, and count are local variables of function process_scores,

QAvgScore and TAvgScoreare local variables of function main.

A local variable may be accessed only inside the body of the function in which it is defined.

Local variables in different functions may even have the same name.

A global variable may be accessed in the body of any function that appears after its definition: In the above program we have the following:

MaxCount

is accessed in function process_scores( ) in lines 18 and 25;

is accessed in function main in lines 34 and 39.

AvgScore

is accessed in function process_scores( ) in line 25;

is accessed in function main in lines 36 and 41.

A global variable is used to share information between functions:

In line 34:Function main stores 8 into global variable MaxCount before it calls function process_score in line 35.

So, in the body of function process_score in lines18, and 25, the value of global variable MaxCount is 8.

In line 39:Function main stores 5 into global variable MaxCount before it calls function process_score in line 40.

So, in the body of function process_score in lines18, and 25, the value of global variable MaxCount is 5.

In line 24:

  • After the first call, function process_scores stores the average score of the quizzes into global variable AvgScore before the control returns back to function mainin line 35.

So, in the body of function main in line 35, the value of global variable AvgScore is the average score of the quizzes.

  • After the second call, function process_scores stores the average score of the tests into global variable AvgScore before the control returns to function main line 40.

So, in the body of function main in line 40, the value of global variable AvgScore is the average score of the tests.

Practice:Exercise 1.

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 in which the function was called.
  1. PlacementA function may be called in a source module only if it has been defined or declared before the call statement.

Practice:Exercise 2: 1 and 3.

Homework:Exercise 2: 2, 4, and 5.

Function Prototype of a void Function without Parameters

You declare a function by using a statement consisting of its function header.

This statement is called function prototype.

Example:

void process_scores();or

void process_scores(void);

You call a void function without parameters by using a statement consisting of its name, followed by the left parenthesis and the right parenthesis, as in the following statement:

process_scores ();

1

1

Figure 2Declaring a void Function without Parameters

Line Number

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

2Program to compute a student’s average score in a marking period

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

4#include <iostream>

5using namespace std;

6void process_scores(void);

//to read quiz/test scoresand compute their average

7int MaxCount;// the number of quizzes or test scores

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

9int main( )

10{

11doubleQAvgScore,//a student’s average quiz score

12TAvgScore;//a student’s average test score

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

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

15MaxCount = 8;

16process_scores ( );

17QAvgScore = AvgScore;

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

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

20MaxCount = 5;

21process_scores ( );

22TAvgScore = AvgScore;

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

24coutendl“the average score is:\t”

25(.3 * QAvgScore + .7 * TAvgScore );

26return 0;

27}

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

29/* read scores and compute their average */

30void process_scores ( )

31{

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

33TotalScore;//a student’s total test or quiz score

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

35TotalScore = 0;

36count = 0;

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

38while (count < MaxCount )

39{

40cin >score;

41TotalScore = TotalScore + score;

42count = count + 1;

43}

44/*------compute the average score ------*/

45AvgScore = TotalScore / MaxCount;

46}

Practice:Exercise 3: 1 and 2a. Homework: Exercise 3: 2b and 2c.

Using Parameters to Share Information between Functions

In addition to use global variables to share information between functions, you may also use parameters to share information between functions.

A C/C++ function may have two types of parameter:

  • value parameters, and
  • reference parameters.

When you define a function, you enclose the parameters and their data types in the parentheses that follow the name of the function in the function header. Two or more parameters are separated with commas.

You use the ampersand ( & ) to distinguish a reference parameter from a value parameter.

Examples:

  • void process_scores(int MaxCount, double & AvgScore)

integer value parameter double precision reference parameter

  • void printresult(int num1, double num2, char letter

integer value parameterdouble precision value parametercharacter value parameter

  • void swapper( int & firstv, int & secondv)

integer reference parameter

You use a value parameter when you want to pass a value to the function:

  • When the function is called, a memory location is created for each value parameter
  • Each memory location is initialized with the corresponding value that is passed to the function.
  • After the execution of the function, memory locations allocated for value parameters are destroyed.

You use a reference parameter when you want the function to have access to a variable defined inside the calling function:

  • When you call the function, you must provide a variable for each reference parameter.
  • The variable that you provide for each reference parameter replaces that parameter in the body of the function

Figure 3Defining and Calling void Functions with Parameters

A.Definition of function:

/*------function computeProdSum( ) ------*/

/*------compute the product and the sum of two integer values and return them ------*/

void computeProdSum(int num1, int num2, int & prod, int & sum)

{

prod = num1 * num2;

sum = num1 + num2;

}

B. Function Calls:

Given the following declaration of variables:int num, fNum = 3, sNum = 4, res1, res2;

We have the following:

Function Calls / Before the Execution
of the Function / After the Execution
of the Function
a.computeProdSum(fNum, sNum, res1, res2); / num1 ←3
num2 ← 4
prod ← res1
sum ← res2 / num1 and num2 are destroyed.
res1 ← 12
res2 ← 7
b.computeProdSum(2, sNum +5, res1, res2); / num1 ← 2
num2 ← 9
prod ← res1
sum ← res2 / num1 and num2 are destroyed.
res1 ← 18
res2 ← 11

Rules for Calling a void Function with Parameters

In the call of a void function with parameters, you must do the following:

  • specify a value for each value parameter:

The value provided and the value parameter must have compatible data types.

  • specify a variable for each reference parameter:

The variable provided and the reference parameter must have the same data type.

Values and variables provided in a function call are called arguments of the function.

The number of arguments must be the same as the number of parameters.

An argument that corresponds to a value parameter may also be an expression: the expression is first evaluated, and its value is passed to the function.

Given the following declaration of variables:

int num, fNum = 3, sNum = 4, res1, res2;

char letter;

The following function calls are invalid:

Function CallsReasons

a.computeProdSum(fNum, res1, res2);// Not enough arguments: an additional value argument is needed

b.computeProdSum(fNum, 9, res1 +2, res2);// the third argument must be a variable name

c. computeProdSum(7, 9, fNum, res1, res2);// more arguments than what is required

d. computeProdSum(2, 7.5, res1, res2);// The second argument must be an integer value

e.computeProdSum(2, 5, letter, res2);// the third argument must be an integer variable

The following call statement is valid; but it will cause a processing error:

computeProdSum(num, 5, res1, res2);// variable num is not initialized

Examples of void Functions with Parameters

1.

/*------function process_list( ) ------*/

/* ------read double precision values, compute their average, and returns it ------*/

void process_list(int MaxCount, double & avge)

{

double value,// to hold a value in the list

totalValue = 0, // to hold the sum of all the values in the list

int count = 0;// to count the values in the list

/*------read the values in the list and compute their sum ------*/

while (count < MaxCount )

{

cin > value;

totalValue = totalValue + value;

count = count + 1;

}

/*------compute the average of the values and return it ------*/

avge = totalValue / MaxCount;

}

2.

/*------function swapper( ) ------*/

/*------interchange the values of two variables if the first is greater than the second ------*/

void swapper(int & num1, int & num2)

{

int temp;

if ( num1 > num2)

{

temp = num1;

num1 = num2;

num2 = temp;

}

}

3.

/*------function getCode ( ) ------*/

/* ------determine the letter code that corresponds to an integer value and return it ------*/

void getCode(int num, char & code)

{

if (num >= 70)

code = ‘S’;

else if (num >= 50)

code = ‘M’;

else if (num >= 30)

code = ‘J’;

else

code = ‘Y’;

}

Practice:Exercise 4.

Tracing the Executing of a Program with Calls to Functions with Parameters

Notes

Each time a function is called, a new memory location is created for each value parameter, and this memory location is initialized with its corresponding argument

Each time a function is called, a reference parameter becomes another name of its corresponding argument.

Figure 4The execution of the following program is provided below:

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

2{

3vnum = vnum + 5;

4rnum1 = rnum1 + 10;

5rnum2 = vnum + rnum1;

6}

7int main( )

8{

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

10num3 = 17;

11process(num1, num2, num4);

12cout < endl“num1 = “num1

“\t num2 = “num2“\t num4 = “num4;

13process(8, num3, num4);

14cout < endl“num3 = “num3“\t num4 = “< num4;

15return ( 0 );

16}

Execution of the Program

Line #Memory Locations

Function main: num1 num2 num3 num4

-69 ??

1069 17?

11Function Process:rnum1 = num2 rnum2 = num4 vnum

-69 17?6

369 17?11

4619 17?11

5619 173011

Function main:

11619 1730

12619 1730

13Function Process: rnum1 = num3rnum2 = num4vnum

-619 17308

3619 173013

4619 273013

5619 274013

Function main:

13619 2740

14619 2740

OUTPUT

num1 = 6num2 = 19num4 = 30

num3 = 27num4 = 40

1

Practice:Exercise 5: 1 and 3a.

Homework:Exercise 5: 2 and 3b, 3c, 3d.

Practice:Exercise 6: problem 1.

Homework:Exercise 6: problem 2.

Function Prototype of a void Function with Parameters

You declare a void function with parameters by using a statement consisting of its function header.

This statement is called function prototype.

Examplesvoid process_list(int MaxCount, double & AvgScore);

The purpose of a function prototype is to specify to the compiler how a call statement for that function must be written.

It is not necessary to specify the parameters in a function prototype. The above function prototypes can also be written as follows:

void process_list(int , double & );

Case Study 2

In this case study, we modify the program to compute students’ average scores in a marking period (written in Figure 1) so that the void function with parameters process_list( ) defined in the above example is called to read a student’s quiz/test scores and compute their average.

Figure 5

Line Number

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

2Program to compute a student’s average score in a marking period

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

4#include <iostream>

5using namespace std;

5void process_list(int, double &);

// to read quiz/test scores, and compute their average

6int main( )

7{

8doubleQAvgScore,//a student’s average quiz score

9TAvgScore;//a student’s average test score

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

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

12process_list(8, QAvgScore);

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

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

15process_list(5, TAvgScore);

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

17coutendl“the average score is:\t”

18(.3 * QAvgScore + .7 * TAvgScore );

19return 0;

20}

21/* ------definition of the function process_list () ------*/

22/* read double precision values, compute their average and return it */ */

23void process_list (int MaxCount, double & avge)

24{

25double value,//to hold a value in the list

26totalValue = 0;//to hold the sum of all the values

27int count;//to count the values in the list

28/*----- read the values in the list and compute their sum ------*/

29while (count < MaxCount )

30{

31cin >value;

32totalValue = totalValue + value;

33count = count + 1;

34}

35/*------compute the average of the values and return it ------*/

36avge = totalValue / MaxCount;

37}

Practice:Exercise 7: 1.

Functions that Return a Value

The only difference between a function that returns a value and a void function is that a function that returns a value must use the return statement to provide a value to the calling function.

The syntax of the function header of a function that returns a value is specified as follows:

  1. Function without Parameters

<retun-type> <function-name>( )

or

<retun-type> <function-name>(void)

  1. Function with Parameters

<retun-type> <function-name> (<type1> <para1>, . . ., <typeN> <paraN>)

-The parameters are specified in the same way as for void functions.

-<retun-type>is the function’s return type.

It is the data type of the value that is provided to the calling function through the return statement.

The following are the basic return types:

  • charvalue returned must be a character value.
  • intvalue returned must be an integer value.
  • floatvalue returned must be a single precision floating-point value.
  • doublevalue returned must be a double precision floating-point value.
  • boolvalue returned must be a Boolean value (true or false).

The following are examples of function headers of functions that return a value:

double process_list2(int MaxCount)

int ComputeProduct(int num1, int num2)

char getCode2(int num)

bool isaletter(char ch )

The return Statement

The body of any function that returns a value must have at least one return statement with the following syntax:

return <expression>;

or

return (<expression>);

expression>is an expression that evaluates to a value whose data type is compatible with the function’s return type.

It is first evaluated, and its value is supplied to the calling function.

The execution of the return statement terminates the execution of the function.

Figure 6Executing the return Statement

Given the following definitions of variables:

char ch = ‘A’;

int num = 5;

double dnum = 7.2;

The following return statements evaluate as follows:

return StatementFunction Return TypeValue Supplied

return ch;charA

return num + 6int11

return dnum - 3double/float4.2

return dnum - 3int4

return num +6double11.0

return (‘0’ <= ch & ch <= ‘9’)boolfalse

The body of a void function may (optionally) have a return statement without any expression with the following syntax:

return;

Figure 7Definitions of Functions with Parameters that Return a Value

1.

/*------function process_list2( ) ------*/

/* ------read double precision values, compute their average, and returns it ------*/

double process_list2(int MaxCount)

{

double value,// to hold a value in the list

totalValue = 0, // to hold the sum of all the values in the list

int count = 0;// to count the values in the list

/*------read the values in the list and compute their sum ------*/

while (count < MaxCount )

{

cin > value;

totalValue = totalValue + value;

count = count + 1;

}

/*------compute the average of the values and return it ------*/

return ( totalValue / MaxCount);

}

2.

/*------function ComputeProd( ) ------*/

/*------compute the product of two integer values and return it ------*/

int ComputeProd(int num1, int num2)

{

int prod;

prod = num1 * num2;

return (prod);

}

3.

/*------function getCode2 ( ) ------*/

/* ------determine the letter code that corresponds to an integer value and return it ------*/

char getCode2(int num)

{

char code;

if (num >= 70)

code = ‘S’;

else if (num >= 50)

code = ‘M’;

else if (num >= 30)

code = ‘J’;

else

code = ‘Y’;

return(code);

}

4.

/*------function isaletter ( ) ------*/

/* ----- determine if a character is a letter of the alphabet: return true if it is; false, otherwise ---*/

bool isaletter(char ch )

{

return (‘A’ <= ch & ch <= ‘Z’ || ‘a’ <= ch & ch <= ‘z’);

}

Calling a Function that returns a Value

You call a function without parameters that returns a value by writing:

function-name( )

in any expression in which the value returned could be written.

Figure 8Calling a Function without Parameters that returns a Value

Given the following definition of function process():

int process(void)

{

return 5:

}

The execution of the following program with calls of function process() will produce the output specified bellow:

int main( )

{

int num1, num2 = 12;

cout < endl < “Result1=\t” < ( process( ) + 4);

num1 = num2 - process( ) ;