Chapter 7
Chapter 7
7. Functions
Second Semester 2023/2024
2
Introduction
3
Functions
4
Predefined Functions
Function type : is the data type of the final value returned by the function.
5
Predefined Functions
Header Parameter(s)
Function Purpose Result
File Type
Returns the absolute value of its
abs(x) int int
argument: abs(-7) = 7
Returns the absolute value of its
fabs(x) double double
argument. fabs(-5.67) = 5.67
<cmath>
6
Predefined Functions
Header Parameter(s)
Function Purpose Result
File Type
x
Returns e , where e = 2.71828
exp(x) double double
exp(1.0) = 2.71828
y
<cmath>
Returns x .
pow(x, y) double double
pow(0.16, 0.5) = 0.4
Returns the nonnegative square root of x
sqrt(x) x must be nonnegative: double double
sqrt(4.0) = 2.0
7
Predefined Functions
Header
Parameter(s)
Function Purpose Result
Type
File
Returns the lowercase value of x if x is int
tolower(x) int
uppercase; otherwise, it returns x char
Returns the uppercase value of x if x int
toupper(x) int
is lowercase; otherwise, it returns x char
<cctype>
8
Predefined Functions
//How to use predefined functions.
#include <iostream>
#include <cmath>
#include <cctype>
using namespace std;
void main( )
{
int x, u, v;
cout << "Line 1: Uppercase a is " << char(toupper(97))<< endl; //Line 1
u = 2; //Line 2
v = 3; //Line 3
cout << "Line 4: "<<u <<" to the power of " << v << "= " <<pow(u, v)<< endl; //Line 4
cout << "Line 5: 3.0 to the power of 2= " << pow(3.0, 2) << endl; //Line 5
u = u + pow(3.0, 3); //Line 6
cout <<"Line 7: u = " << u << endl; //Line 7
x = -15; //Line 8
cout << "Line 9: Absolute value of " << x << "= " << abs(x) << endl; //Line 9
}
9
User-Defined Functions
User-Defined Functions
Because C++ does not provide every function that you will ever
need and designers cannot possibly know a user’s specific needs,
you must learn to write your own functions.
11
User-Defined Functions
12
Value-Returning Functions
Some predefined C++ functions such as pow, abs, islower, and
toupper are examples of value-returning functions.
To use these functions in your programs, you must know the name of
the header file, and know the following items:
1. The name of the function
header function
Heading or
13
Value-Returning Functions
Because the value returned by a value-returning function is
unique, the natural thing for you to do is to use the value in one
of three ways:
Save the value for further calculation.
Use the value in some calculation.
Print the value.
14
Value-Returning Functions
Example: Function abs.
The function abs might have the following definition:
4 1 2
Header int abs(int number) 1. The name of the function
3 2. The number of parameters, if any
{ 3. The data type of each parameter
if (number < 0) 4. The data type of the value computed
5. Body
16
Value-Returning Functions
int abs(int number)
{
if (number < 0)
number = -number;
return number;
}
int a = -15;
cout<< "Absolute value of " << a << " = " << abs(a) << endl; //Line 1
cout << "Absolute value of " << -16 << " = " << abs(-16) << endl; //Line 2
17
Value-Returning Functions
Formal Parameter: A variable declared in the function heading.
Actual Parameter: A variable or expression listed in a call to a function.
19
Value-Returning Functions
A function’s formal parameter list can be empty.
if the formal parameter list is empty, the parentheses are still
needed.
The syntax of the function heading, if the formal parameter list is
empty, as the following form:
20
Value-Returning Functions
21
Value-Returning Functions
return Statement
Once a value-returning function computes the value, the function
returns this value via the return statement. In other words, it
passes this value outside the function via the return statement.
22
Value-Returning Functions
23
Value-Returning Functions
double larger(double x, double y)
{ double max;
if (x >= y) max = x;
else max = y;
return max; }
The function larger requires that you use an additional variable max
(called a local declaration, in which max is a variable local to the
function larger).
24
Value-Returning Functions
The following figure describes various parts of the function larger.
25
Value-Returning Functions
You can also write the definition of the function larger as follows:
Note that these forms of the function larger do not require you to
declare any local variable.
The return statement can appear anywhere in the function. Once a
return statement executes, all subsequent statements are
skippedment
27
Value-Returning Functions
Example:
The following C++ code illustrates how to use the function larger.
double larger(double x, double y)
{ if (x >= y)
return x;
else return y; }
Consider the following statements:
double one = 13.00;
double two = 36.53;
double maxNum;
cout << "The larger of 5 and 6 is " << larger(5, 6) << endl; //Line 1
cout << "The larger of " << one<< "&" << two << "is" << larger(one, two); //Line 2
cout << " \n The larger of " << one << " and 29 is " << larger(one, 29) ; //Line 3
cout <<"\n"; //Line 4
maxNum = larger(38.45, 56.78); //Line 5
28
Value-Returning Functions
29
Value-Returning Functions
The expression larger(one, two) in Line 2 is a function call.
Here, one and two are actual parameters. When the expression
larger(one, two) executes, the value of one is copied into x, and the
value of two is copied into y. Therefore, the statement in Line 2 outputs
the larger of one and two.
30
Value-Returning Functions
31
Value-Returning Functions
Note: In a function call, you specify only the actual parameter, not its
data type.
Example:
- The statements in Lines 1, 2, 3, and 5 show how to call the function
larger with the actual parameters.
32
Value-Returning Functions
33
Value-Returning Functions
Let us take a look at the expression: larger( x, larger(y, z) )
This expression has two calls to the function larger.
The actual parameters to the outer call are x and larger(y, z); the actual
parameters to the inner call are y and z.
It follows that, first, the expression larger(y, z) is evaluated; that is, the
inner call executes first, which gives the larger of y and z.
Suppose that larger(y, z) evaluates to, say, t. (Notice that t is either y or z.)
Next, the outer call determines the larger of x and t.
Finally, the return statement returns the largest number.
It thus follows that to execute a function call, the parameters are evaluated
first.
34
Function Prototype
Now that you have some idea of how to write and use functions in a
program, the next question relates to the order in which user-
defined functions should appear in a program.
Example:
Do you place the function larger before or after the function main?
Should larger be placed before compareThree or after it?
Following the rule that you must declare an identifier before you
can use it and knowing that the function main uses the identifier
larger, logically you must place larger before main.
35
Function Prototype
36
Function Prototype
For example, if the function main is placed before the function
larger, the identifier larger is undefined when the function main is
compiled. To work around this problem of undeclared identifiers,
we place function prototypes before any function definition
(including the definition of main).
37
Function Prototype
The general syntax of the function prototype of a value-returning
function is:
Note: When writing the function prototype, you do not have to specify
the variable name in the parameter list. However, you must specify the
data type of each parameter.
You can rewrite the function prototype of the function larger as follows:
double larger(double, double);
38
//Program: Largest of three numbers
#include <iostream>
using namespace std;
double larger(double x, double y);
double compareThree(double x, double y, double z);
void main( )
{ double one, two; //Line 1
cout << "Line 2: The larger of 5 and 10 is " << larger(5, 10) << endl; //Line2
cout << "Line 3: Enter two numbers: "; //Line 3
cin >> one >> two; //Line 4
cout <<" The larger of"<<one<<"&"<<two<< "is "<<larger(one, two)<<endl ; //Line5
cout<<"The largest of 43.48, 34.00, & 12.65 is"<<compareThree(43.48, 34.00, 12.65); //Line6
}
double larger(double x, double y)
{ double max;
if (x >= y) max = x;
else max = y;
return max; }
double compareThree (double x, double y, double z)
{ return larger(x, larger(y, z)); } 39
Value-Returning Functions: Some Peculiarity
40
Value-Returning Functions: Some Peculiarity
int secret(int x)
{
if (x > 5) //Line 1
return 2 * x; //Line 2
}
42
Value-Returning Functions: Some Peculiarity
2. Consider the following return statement:
43
Value-Returning Functions: Some Peculiarity
/* This program illustrates that a value-returning function returns only one value,
even if the return statement contains more than one expression.*/
int funcRet1( );
int funcRet2(int z);
int main( )
{ int num = 4;
cout << "Line 1:The value returned by funcRet1: " << funcRet1() << endl; // Line 1
cout << "Line 2:The value returned by funcRet2: "<< funcRet2(num) << endl; // Line 2
}
int funcRet1( )
{ int x = 45;
return 23, x; //only the value of x is returned
}
int funcRet2(int z)
{ int a = 2;
int b = 3;
return 2 * a + b, z + b; //only the value of z + b is returned
} 44
Void Functions
45
Void Functions
46
Void Functions
Because void functions do not have a data type, they are not used
(called) in an expression.
47
Void Functions
48
Void Functions
You must specify both the data type and the variable name in the
formal parameter list.
The symbol & after dataType has a special meaning; it is used
only for certain formal parameters.
49
Void Functions
Function Call: The function call has the following syntax:
Actual Parameter List: The actual parameter list has the following
syntax:
50
Void Functions
Parameters provide a communication link between the calling
function (such as main) and the called function.
They enable functions to manipulate different data each time
they are called.
Example:
void expfun(int one, int& two, char three, double& four)
{
.
.
}
53
Value Parameters
//Program illustrating how a value parameter works.
#include <iostream>
using namespace std;
void funcValueParam(int num)
{
cout <<"In the function funcValueParam, before changing, num= " << num << endl;
num = 15;
cout<<"In the function funcValueParam, after changing, num = " << num << endl;
}
void main( )
{ int number = 6;
cout<<"Before calling the function funcValueParam, number=" <<number<< endl;
funcValueParam(number);
cout<<"After calling the function funcValueParam, number= " <<number<< endl;
}
54
Reference Variables as Parameters – Example #1
//This program reads a course score and prints the associated course grade.
void getScore(int& score) //line 1
{ cout << "Enter course score: "; cin >> score; //line 2
cout << endl << "Course score is "<<score<<endl; //line 3
}
void printGrade(int cScore) //line 4
{ cout<<"Your grade for the course is "; //line 5
if (cScore >= 90) cout << "A." << endl; //line 6
else if (cScore >= 80) cout << "B." << endl;
else if(cScore >= 70) cout << "C." << endl;
else if (cScore >= 60) cout << "D." << endl;
else cout << "F." << endl; }
int main( )
{ int courseScore; //line 7
cout<<"Based on the course score,\n this program computes the course grade."<<endl; //line 8
getScore(courseScore); //line 9
printGrade(courseScore); //line 10 55
return 0; }
Reference Variables as Parameters – Example #1
The program starts to execute at Line 8, which prints the first line of
the output.
The statement in Line 9 calls the function getScore with the actual
parameter courseScore (a variable declared in main).
Because the formal parameter score of the function getScore is a
reference parameter, the address (that is, the memory location of the
variable courseScore) passes to score. Thus, both score and
courseScore refer to the same memory location, which is courseScore
getScore(courseScore); //line 9
The statement in Line 2 reads and stores the value entered by the
user (85 in the sample run) in score, which is actually courseScore
(because score is a reference parameter). Thus, at this point, the
value of the variables score and courseScore is 85 (see the following
figure).
57
Reference Variables as Parameters – Example #1
58
Reference Variables as Parameters – Example #1
The statement in Line 10 executes next. It is a function call to the function
printGrade with the actual parameter courseScore. Because the formal
parameter cScore of the function printScore is a value parameter, the
parameter cScore receives the value of the corresponding actual parameter
courseScore.
Thus, the value of cScore is 85. After copying the value of courseScore into
cScore, no communication exists between cScore and courseScore
(see the following figure ).
printGrade(courseScore); //line 10
The program then executes the statement in Line 5, which outputs the fourth line.
The if. . .else statement in Line 6 determines and outputs the grade for the
course. Because the output statement in Line 5 does not contain the newline
character or the manipulator endl, the output of the if. . .else statement is part of
the fourth line of the output.
After the if...else statement executes, control goes back to the function main.
Because the next statement to execute in the function main is the last statement
of the function main, the program terminates.
60
Reference Variables as Parameters – Example #1
In this program, the function main first calls the function getScore to obtain
the course score from the user. The function main then calls the function
printGrade to calculate and print the grade based on this course score.
The course score is retrieved by the function getScore; later, this course
score is used by the function printGrade. Because the value retrieved by the
getScore function is used later in the program, the function getScore must
pass this value outside. Thus, the formal parameter that holds this value
must be a reference parameter.
61
void funOne(int a, int& b, char v); Example #2
void funTwo(int& x, int y, char& w);
void main( )
{ int num1, num2;
char ch;
num1 = 10; //Line 1
num2 = 15; //Line 2
ch = 'A'; //Line 3
cout<<"Line 4:Inside main:num1 = "<<num1<<", num2= "<<num2<<", and ch= "<<ch<<endl; //Line 4
funOne(num1, num2, ch); //Line 5
cout << "Line 6: After funOne: num1= "<<num1<<", num2= "<<num2<<", and ch= "<<ch<<endl; //Line 6
funTwo(num2, 25, ch); //Line 7
cout << "Line 8: After funTwo: num1= "<<num1<<", num2= "<<num2<<", and ch= "<<ch<<endl; //Line 8
}
void funOne(int a, int& b, char v)
{ int one;
one = a; //Line 9
a++; //Line 10
b = b * 2; //Line 11
v = 'B'; //Line 12
cout << "Line 13:Inside funOne:a= "<<a<<", b= "<<b<<", v= "<<v<<", and one= "<<one<<endl; //Line 13
}
void funTwo(int& x, int y, char& w)
{ x++; //Line 14
y = y * 2; //Line 15
w = 'G'; //Line 16 62
cout << "Line 17:Inside funTwo: x= "<<x<<",y= "<<y<<", and w= "<<w<<endl; //Line 17
}
Example #2
After the statement in Line 10, a++;, executes, the variables are as shown in
following figure. a++; //Line 10
After the statement in Line 11, b = b * 2;, executes, the variables are as shown
in following figure . (Note that the variable b changed the value of num2.)
b = b * 2; //Line 11
65
After the statement in Line 12, v = 'B';, executes, the variables are as shown in
following figure.
v = 'B'; //Line 12
After the statement in Line 13 executes, control goes back to Line 6 and the
memory allocated for the variables of function funOne is deallocated.
The following figure shows the values of the variables of the function main.
66
cout << "Line 13:Inside funOne:a= "<<a<<", b= "<<b<<", v= "<<v<<", and one= "<<one<<endl; //Line 13
Example #2
Line 6 produces the following output:
Line 6: After funOne: num1 = 10, num2 = 30, and ch = A
The following figure shows the values before the statement in Line 14 executes.
funTwo(num2, 25, ch); //Line 7
void funTwo(int& x, int y, char& w)
{
x++; //Line 14
y = y * 2; //Line 15
w = 'G'; //Line 16
cout << "Line 17:Inside funTwo: x= "<<x<<",y= "<<y<<", and w= "<<w<<endl;67 //Line 17
}
Example #2
After the statement in Line 14, x++;, executes, the variables are as shown in
the following figure. (Note that the variable x changed the value of num2.)
x++; //Line 14
68
Example #2
After the statement in Line 15, y = y *2; , executes, the variables are as
shown in the following figure.
y = y * 2; //Line 15
w = 'G'; //Line 16
cout << "Line 17:Inside funTwo: x= "<<x<<",y= "<<y<<", and w= "<<w<<endl; //Line 17