Module 10 - User-Defined Functions 1
Module 10 - User-Defined Functions 1
MODULE 10
User-defined Functions 1
Jholan O. Sabaria
Instructor I-COS
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Objective/s
At the end of this module students will be able to :
Lesson
C++ program is a collection of functions. One such function is main. The programs from previous lessons use only the
function main; the programming instructions are packed into one function. This technique, however, is good only for
short programs. For large programs, it is not practical (although it is possible) to put the entire programming instructions
into one function. You must learn to break the problem into manageable pieces.
Functions are like building blocks. They let you divide complicated programs into manageable pieces. They have other
advantages, too:
• While working on one function, you can focus on just that part of the program and construct it, debug it, and
perfect it.
• Different people can work on different functions simultaneously.
• If a function is needed in more than one place in a program or in different programs, you can write it once and
use it many times.
• Using functions greatly enhances the program’s readability because it reduces the complexity of the function
main.
•
Functions are often called modules. They are like miniature programs; you can put them together to form a larger
program.
1 Predefined Functions
In algebra, a function can be considered a rule or correspondence between values, called the function’s arguments, and
the unique values of the function associated with the arguments. Thus, if f ( x)=2 x +5 , then f (1)=7 , f (2)=9 ,
and f (3)=11 , where 1, 2, and 3 are the arguments of f , and 7, 9, and 11 are the corresponding values of the
function f .
In C++, the concept of a function, either predefined or user-defined, is similar to that of a function in algebra. For
example, every function has a name and, depending on the values specified by the user, it does some computation.
In C++, predefined functions are organized into separate libraries. For example, the header file iostream contains I/O
functions, and the header file cmath contains math functions.
Table 1 lists some of the predefined functions, the name of the header file in which each function’s specification can be
found, the data type of the parameters, and the function type. The function type is the data type of the final value
returned by the function.
2021 Page 1 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
The predefined functions included in Table 1 are just some of commonly used functions. But there are a lot more
predefined functions in the C++ Standard Library. You can visit https://en.cppreference.com/ to check them.
To use predefined functions in a program, you must include the header file that contains the function’s specification via
the include statement. For example, to use the function pow(), the program must include:
#include <cmath>
Example 1
#include <cctype>
#include <cmath>
#include <iomanip>
#include <iostream>
int main() {
int num;
double firstNum, secondNum;
2021 Page 2 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
char ch = 'T';
cout << firstNum << " to the power of " << secondNum << " = "
<< pow(firstNum, secondNum) << endl;
cout << "5.0 to the power of 4 = " << pow(5.0, 4) << endl;
num = -32;
cout << "Absolute value of " << num << " = " << abs(num) << endl;
cout << "Square root of 28.00 = " << sqrt(28.00) << endl;
return 0;
}
2 User-defined Functions
As Example 1 illustrates, using functions in a program greatly enhances the program’s readability because it reduces the
complexity of the function main. Also, once you write and properly debug a function, you can use it in the program (or
different programs) again and again without having to rewrite the same code repeatedly. For instance, in Example 1, the
function pow() is used more than once.
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.
• Value-returning functions – functions that have a return type. These functions return a value of a specific data
type using the return statement, which we will explain shortly.
• Void functions – functions that do not have a return type. These functions do not use a return statement to return
a value.
When using or creating a value-value returning functions you must know the following:
2021 Page 3 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
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. For example, x = pow(3.0, 2.5);
• Use the value in some calculation. For example, area = PI * pow(radius, 2.0);
• Print the value. For example, cout << abs(-5) << endl;
• In an assignment statement.
• As a parameter in a function call.
• In an output statement.
In addition to the four properties described previously, one more thing is associated with functions (both value-returning
and void):
The first four properties form what is called the heading of the function (also called the function header); the fifth
property is called the body of the function. Together, these five properties form what is called the definition of the
function (or function definition). For example, for the function abs, the heading might look like:
The variable declared in the heading of the function abs is called the formal parameter of the function abs. Thus, the
formal parameter of abs is number. The program in Example 1 contains several statements that use the function pow.
That is, in C++ terminology, the function pow is called several times.
From the heading of the function pow, it follows that the formal parameters of pow are base and exponent. Consider the
following statements:
double u = 2.5;
double v = 3.0;
double x, y;
x = pow(u, v); //Line 1
2021 Page 4 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
In Line 1, the function pow is “called” (function call) with the parameters u and v. In this case, the values of u and v
are passed to the function pow. In fact, the value of u is copied into base, and the value of v is copied into exponent. The
variables u and v that appear in the call to the function pow in Line 1 are called the actual parameters of that call. In
Line 2, the function pow is called with the parameters 2.0 and 3.2. In this call, the value 2.0 is copied into base, and
3.2 is copied into exponent. Moreover, in this call of the function pow, the actual parameters are 2.0 and 3.2,
respectively. Similarly, in Line 3, the actual parameters of the function pow are u and 7; the value of u is copied into
base, and 7.0 is copied into exponent.
Note:
Actual Parameter is also called as Argument
For predefined functions, you only need to be concerned with the first four properties. You don’t need to worry about
how the predefined functions were implemented. In programming this way of hiding the detailed implementation is
known as abstraction.
in which statements are usually declaration statements and/or executable statements. In this syntax, functionType is
the type of the value that the function returns. The functionType is also called the data type or the return
type of the value-returning function. Moreover, statements enclosed between curly braces form the body of the
function.
Consider the definition of the function abs given earlier in this chapter. Figure 1 identifies various parts of this function.
2021 Page 5 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
(In this syntax, expression can be a single constant value.) Thus, to call a value- returning function, you use its name,
with the actual parameters (if any) in parentheses.
A function’s formal parameter list can be empty. However, if the formal parameter list is empty, the parentheses are still
needed. The function heading of the value-returning function thus takes, if the formal parameter list is empty, the
following form:
functionType functionName()
If the formal parameter list of a value-returning function is empty, the actual parameter is also empty in a function call.
In this case (that is, an empty formal parameter list), in a function call, the empty parentheses are still needed. Thus, a
call to a value-returning function with an empty formal parameter list is:
functionName()
In a function call, the number of actual parameters, together with their data types, must match with the formal parameters
in the order given. That is, actual and formal parameters have a one-to-one correspondence.
As stated previously, a value-returning function is called in an expression. The expression can be part of either an
assignment statement or an output statement, or a parameter in a function call. A function call in a program causes the
body of the called function to execute.
2021 Page 6 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
return expr;
in which expr is a variable, constant value, or expression. The expr is evaluated, and its value is returned. The data
type of the value that expr computes must match the function type.
When a return statement executes in a function, the function immediately terminates and the control goes back to the
caller. Moreover, the function call statement is replaced by the value returned by the return statement. When a return
statement executes in the function main, the program terminates.
Let us write a function that determines the larger of two numbers. Because the function compares two numbers, it
follows that this function has two parameters and that both parameters are numbers. Let us assume that the data type of
these numbers is floating-point (decimal) – say, double. Because the larger number is of type double, the function’s
data type is also double. Let us name this function larger. The only thing you need to complete this function is the
body of the function. Thus, following the syntax of a function, you can write this function as follows:
if (x >= y)
max = x;
else
max = y;
return max;
}
Note that the function larger uses an additional variable max (called a local declaration, in which max is a variable local
to the function larger). Figure 2 describes various parts of the function larger.
2021 Page 7 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Suppose that num, num1, and num2 are double variables. Also suppose that num1 = 45.75 and num2 = 35.50.
Figure 3 shows various calls to the function larger.
You can also write the definition of the function larger as follows:
Because the execution of a return statement in a function terminates the function, the preceding function larger can also
be written (without the word else) as:
Note that these forms of the function larger do not require you to declare any local variable.
Note:
1. In the definition of the function larger, x and y are formal parameters.
2. The return statement can appear anywhere in the function. Recall that once a return
statement executes, all subsequent statements are skipped. Thus, it’s a good idea to return the value as
soon as it is computed.
Example 2
Now that the function larger is written, the following C++ code illustrates how to use it:
2021 Page 8 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
cout << "The larger of 5 and 6 is " << larger(5, 6) << endl; //Line 1
cout << "The larger of " << one << " and " << two
<< " is " << larger(one, two) << endl; //Line 2
cout << "The larger of " << one << " and 29 is "
<< larger(one, 29) << endl; //Line 3
• The expression larger(5, 6) in Line 1 is a function call, and 5 and 6 are actual parameters. When the
expression larger(5, 6) executes, 5 is copied into x, and 6 is copied into y. Therefore, the statement in
Line 1 outputs the larger of 5 and 6.
• 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.
• The expression larger(one, 29) in Line 3 is also a function call. When the expression larger(one,
29) executes, the value of one is copied into x, and 29 is copied into y. Therefore, the statement in Line 3
outputs the larger of one and 29. Note that the first parameter, one, is a variable, while the second parameter, 29,
is a constant value.
• The expression larger(38.45, 56.78) in Line 4 is a function call. In this call, the actual parameters are
38.45 and 56.78. In this statement, the value returned by the function larger is assigned to the variable
maxNum.
Once a function is written, you can use it anywhere in the program. The function larger compares two numbers and
returns the larger of the two. Let us now write another function that uses this function to determine the largest of three
numbers. We call this function compareThree.
in the definition of the function compareThree. 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. For example, the actual parameter
larger(y, z) of the outer call evaluates first.
2021 Page 9 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Note that the function larger is much more general purpose than the function compareThree. Here, we are merely
illustrating that once you have written a function, you can use it to write other functions. Later, we will show how to use
the function larger to determine the largest number from a set of numbers.
Note
1. In the definition of the function larger, x and y are formal parameters.
2. The return statement can appear anywhere in the function. Recall that once a return statement executes, all
subsequent statements are skipped. Thus, it’s a good idea to return the value as soon as it is computed.
Example 2
Now that the function larger is written, the following C++ code illustrates how to use it:
• The expression larger(5, 6) in Line 1 is a function call, and 5 and 6 are actual parameters.
When the expression larger(5, 6) executes, 5 is copied into x, and 6 is copied into y. Therefore,
the statement in Line 1 outputs the larger of 5 and 6.
• 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.
• The expression larger(one, 29) in Line 3 is also a function call. When the expression
larger(one, 29) executes, the value of one is copied into x, and 29 is copied into y. Therefore,
the statement in Line 3 outputs the larger of one and 29. Note that the first parameter, one, is a
variable, while the second parameter, 29, is a constant value.
• The expression larger(38.45, 56.78) in Line 4 is a function call. In this call, the actual
parameters are 38.45 and 56.78. In this statement, the value returned by the function larger is
assigned to the variable maxNum.
Once a function is written, you can use it anywhere in the program. The function larger compares two numbers and
returns the larger of the two. Let us now write another function that uses this function to determine the largest of three
numbers. We call this function compareThree.
2021 Page 10 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
in the definition of the function compareThree. 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. For example, the actual parameter larger(y,
z) of the outer call evaluates first.
Note that the function larger is much more general purpose than the function compareThree. Here, we are merely
illustrating that once you have written a function, you can use it to write other functions.
In reality, C++ programmers customarily place the function main before all other user-defined functions. However, this
organization could produce a compilation error because functions are compiled in the order in which they appear in the
program. 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()).
Function Prototype: The function heading without the body of the function.
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:
Final Program
You now know enough to write the entire program, compile it, and run it. The following program uses the
functions larger(), compareThree(), and main() to determine the larger/largest of two or three
numbers.
#include <iostream>
2021 Page 11 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
int main() {
cout << "The larger of 5 and 10 is " << larger(5, 10) << endl;
cout << "Enter two numbers: ";
cout << "The larger of " << one << " and " << two << " is "
<< larger(one, two) << endl;
return 0;
}
double max;
if (x >= y)
max = x;
else
max = y;
return max;
}
Sample Run:
if (x > 5) //Line 1
return 2 * x; //Line 2
2021 Page 12 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Because this is a value-returning function of type int, it must return a value of type int. Suppose the value of x is 10.
Then the expression x > 5 in Line 1 evaluates to true. So the return statement in Line 2 returns the value 20. Now
suppose that x is 3. The expression x > 5 in Line 1 now evaluates to false. The if statement therefore fails, and the
return statement in Line 2 does not execute. However, there are no more statements to be executed in the body of the
function. In this case, the function returns a strange value. It thus follows that if the value of x is less than or equal to 5,
the function does not contain any valid return statements to return the value of x.
if (x > 5) //Line 1
return 2 * x; //Line 2
return x; //Line 3
}
Here, if the value of x is less than or equal to 5, the return statement in Line 3 executes, which returns the value of x.
On the other hand, if the value of x is, say 10, the return statement in Line 2 executes, which returns the value 20 and
also terminates the function.
Recall that in a value-returning function, the return statement returns the value. Consider the following return
statement:
This is a legal return statement. You might think that this return statement is returning the values of x and y. However,
this is not the case. Remember, a return statement returns only one value, even if the return statement contains more
than one expression. If a return statement contains more than one expression, only the value of the last expression is
returned. Therefore, in the case of the above return statement, the value of y is returned. The following program further
illustrates this concept:
#include <iostream>
int funcRet1();
int funcRet2(int z);
int main() {
int num = 4;
cout << "The value returned by funcRet1: " << funcRet1() << endl;
cout << "The value returned by funcRet2: " << funcRet2(num) << endl;
return 0;
}
int funcRet1() {
int x = 45;
return 23, x;
}
int funcRet2(int z) {
int a = 2;
int b = 3;
2021 Page 13 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Sample Run:
Even though a return statement can contain more than one expression, a return statement in your program should contain
only one expression. Having more than one expression in a return statement may result in redundancy, wasted code, and
a confusing syntax.
Function prototypes appear before any function definition, so the compiler translates these first. The compiler can then
correctly translate a function call. However, when the program executes, the first statement in the function main()
always executes first, regardless of where in the program the function main() is placed. Other functions execute only
when they are called.
A function call statement transfers control to the first statement in the body of the function. In general, after the last
statement of the called function executes, control is passed back to the point immediately following the function call. A
value-returning function returns a value. Therefore, after executing the value-returning function, when the control goes
back to the caller, the value that the function returns replaces the function call statement. The execution continues at the
point immediately following the function call.
Suppose that a program contains functions funcA and funcB, and funcA contains a statement that calls funcB. Suppose
that the program calls funcA. When the statement that contains a call to funcB executes, funcB executes, and while
funcB is executing, the execution of the current call of funcA is on hold until funcB is done.
3 Programming Examples
All the examples below will use user-defined functions in the solutions’ implementation.
Palindrome is a word, phrase or sentence that reads the same for ward or backward. Example of palindrome strings are
the word “radar”, “ma’am”, “kayak”, “level”, “mom”, “rotator” and “madam”. Now your task is to write a program that
will determine if the string entered by the user is a palindrome or not.
1. START
2. DECLARE index AS INTEGER, line AS STRING
3. SET index TO 0
4. INPUT line
5. WHILE index <= (length of line)/2 DO
5.1 IF line[index] != line[length of line - 1 - index] DO
2021 Page 14 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Note: The pseudocode here implement only the function to check if the given integer is palindrome or not. This does not
represent the whole program.
#include <iostream>
int main() {
return 0;
}
int index = 0;
index++;
}
return true;
}
Type this code to your IDE and while typing study it carefully.
Program Run 1
Program Run 2
2021 Page 15 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Program Run 3
Heron’s formula is the formula for calculating the area of a triangle given the valid measurement of its three sides. The
formula is defined as follow:
Where:
a, b, and c are the valid measurement of the sides of the triangle
a+b+ c
and p is the half of the perimeter, or
2
Now, write a program that check if the given measurements of the sides of a triangle are valid. If it is valid, use the
Heron’s formula to calculate its area, then output the calculated area.
2. FUNCTION areValidSides RETURNING BOOLEAN PARAMETERS: FLOAT side1, FLOAT side2, FLOAT side3 DO
2.1 IF (side1 + side2 > side3) AND (side1 + side3 > side2) AND (side2 + side3 > side1) DO
2.1.1 RETURN true
2.3 END IF
2.4 RETURN FALSE
3. END FUNCTION
4. FUNCTION areaTriangle RETURNING FLOAT PARAMETERS: FLOAT side1, FLOAT side2, FLOAT side3 DO
4.1 DECLARE half_perim AS FLOAT
4.2 SET half_perim TO (side1 + side2 + side3) / 2
4.3 RETURN SQRT(half_perim * (half_perim–side1) * (half_perim–side2) * (half_perim–side3) )
5. END FUNCTION
9. INPUT: input_side1
10. INPUT: input_side2
11. INPUT: input_side3
13. ELSE
13.1 OUTPUT "invalid measurement of sides"
14. END IF
15. END PROGRAM
2021 Page 16 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
#include <cmath>
#include <iostream>
// function prototype
bool areValidSides(float side1, float side2, float side3);
float areaTriangle(float side1, float side2, float side3);
int main() {
else
cout << "Invalid measurement of the sides.\n";
return 0;
}
/* function definitions */
// function to check if sides are valid
bool areValidSides(float side1, float side2, float side3) {
if ((side1 + side2) > side3 && (side1 + side3) > side2 &&
(side2 + side3) > side1)
return true;
return false;
}
Program Run 1
Program Run 2
Program Run 3
2021 Page 17 of 19
CC2-1 - Fundamentals of Programming/CC2 – Computer Programming 1 Module 10: User-defined Functions 1
Reference
Cplusplus.com. (n.d.). Cplusplus.Com. Retrieved June 18, 2021, from http://www.cplusplus.com/
Deitel, P., & Deitel, H. (2014). C++ How to Program (9th ed.). Pearson. www.deitel.com
Hansen, J. (2013). The Rook’s Guide to C++. Rook’s Guide Press. http://creativecommons.org/licenses/by-nc-
sa/3.0/legalcode
Learn C++ Programming Language. (n.d.). Tutorials Point. Retrieved June 18, 2021, from
https://www.tutorialspoint.com/cplusplus/index.htm
LearnCpp.com. (n.d.). Learncpp.Com. Retrieved June 18, 2021, from https://www.learncpp.com/
Learning C++. (n.d.). Retrieved June 18, 2021, from http://www.riptutorial.com/