Unit 13:FUNCTIONS IN C++ PROGRAMMING
Key Unit Competency
By the end of the unit, you should be able to define and use functions in C++ program.Unit Outline
• Fundamentals of C++ Functions.
• Types of functions.
• User-defined functions.
• Function declaration.
• Recursive functionsIntroduction
Structured programming employs a top-down design approach in which the overall program is broken down into separate units called modules, procedures or functions. In the previous unit, we have demonstrated how C++ implements structured programming using structures called control statements within a function called main.
In this unit, we demonstrate how a program can further be structured to more than one functions. To start with, we review basic concepts of modular programming, followed by detailed examination of library and user-defined functions. Finally, we demonstrate how C++ supports recursive functions inherent in procedural programming languages.13.1 Fundamentals of C++ Functions
Top-down approach in structured programming emphasizes on breaking down a program into smaller manageable components known as modules, procedures or functions. In C++, the smallest component having independent functionality is
known as a function. Every C++ program has at least one function called main through which other functions interact with each other directly or indirectly. This interaction is made possible through function calls and parameter passing discussed later in this unit.13.1.1 Features of C++ Functions
Like in other structured programming languages, the following are characteristics of C++ functions:
• A function is a complete sub-program in itself that may contain input, processing and output logic.
• A function is designed to perform a well defined task.
• A function can be compiled, tested and debugged separately without the intervention of other functions.• A function has only one entry and one exit point.
• A function can interact with other functions using a mechanism known as function call and parameter passing.
• A function is designed in such a manner that it can be used with different programs or software system.
• The calling function is suspended during the execution of the called function.
This implies that there is only one function in execution at an y given time.
• Control is always returned to the caller when the function execution terminates.13.1.2 Benefits of using Function
Structured i:e modular programs have several benefits over non-modular programs (monolithic). Some of these benefits include:
• A structured program is easier to understand and test because it is made up of smaller manageable sub-programs than monolithic programs.
• It is easier to modify a structured program by adding or replacing some functions without affecting the entire program.
• Programmers productivity is increased, because each program function can be developed separately by several programmers.
• Structured approach to designing programs enhance the readability of a program.
• Functions can be saved as library functions to be used in other programs hence saving development time and cost.13.1.3 Limitations of using Functions
Although benefits of structured programming outways those of monolithic programming, the following are disadvantages associated with this approach:
• Structured programs need more memory space and extra time for execution. Because some functions repeat the task performed by other functions.
• Integration of various functions into a single program may be difficult because different people working on different modules may not use the same style.
• Testing and debugging of separate functions may be time consuming, thus reducing efficiency of a program.
• Global sharing of data by multiple functions is dangerous because one function can modify a global variable in a way that is invisible to anot her function.13.2 Types of Functions
Functions may be classified into two categories namely: Library or (built-in)functions and user-defined functions. Library function are compiled and put in C++ library to simplify programming task while user-defined function are the functions that we write to create a modular program.13.2.1 Library functions
So far, we have been writing programs by first including (importing) functions from C++ Standard Library. C++ Standard Library provides a collection of predefined functions for common input and output manipulation, calculations, error checking and many other useful operations. To use a library function, we first include its header file, then use a function that passes list of arguments from the calling portion of the program. For example, to find the square root of a number, we use square root function sqrt() as follows:root = sqrt(16);
The function sqrt() evaluates the square root of 16 and returns 4 which is then assigned
to the root. In this section, we demonstrate how to use mathematical, string and character manipulation functions.13.2.1.1 Math Functions
The C++ Library provides a collection of Math functions used to perform mathematical and trigonometric computations. For example, to raise 5 to power 3, we use the pow() function as follows:power = pow(5,3);//returns 125
Table 13.1 enumerates frequently used functions that require inclusion or importing of <cmath> or <math.h> header file using #include directive.
The program below uses two functions i.e. sqrt() and pow() to calculate hypotenuse of a right angled triangle: using the following expression:
The illustration of Fig 13.1 shows the output after running the program.
NB: To use the sqrt() function in the assignment statement, you must include <math> preprocessor directive as shown in the program.
13.2.1.2 Character Functions
Although a computer is a numerical machine, most often, data entered into a computer consist of numbers, characters and strings. The underlying fact is that characters are treated as integers. The C++ Library has in-built functions used to manipulate characters. The functions can be accessed by including <cctype> header file. For example, to convert a character c from uppercase to lower case, we use the following statement:letter = tolower(c)
For example, the program below uses tolower() function to convert a character from uppercase to lowercase.
#include <iostream>
#include <cctype>
using namespace std;int main(){
char letter, small;
cout << “Enter letters A-Z in uppercase:”;
cin >> letter; // read a from keyboard
small = tolower(letter);
cout << letter<<”lowercase is:”<<small<< endl;
return 0;
}Fig. 13.2 shows a sample output once the user enters H as the input. The character is converted to uppercase.
Table 13.2 below gives a summary of frequently used character manipulation functions accessible by including <cctype> header file.
The following program demonstrates how digital() and alpha() functions are used to test whether the user input is a letter or a number.
#include <iostream>
using namespace std;
int main(){
char grade;
cout << “Enter letters or number:”;
cin >> grade; // read a from keyboard
if (isdigit(grade)){
cout<<”The entry”<<grade<<”is number”<<endl;
}else if(isalpha(grade)){
cout<<”The entry grade is”<<grade<<endl;
}
else {
cout<<grade<<”may be a symbol”<<endl;
}
return 0;
}The output after entering a letter and a numeric value is shown in Fig.13.3 below:
13.2.1.3 String Functions
The string-handling library provides many useful functions for manipulating string data, comparing strings, searching strings for characters and substrings. To use the string manipulation functions, you must include the <cstring> header file. For example, the following statement returns the number of characters in “My House” string:The sample output shown in Fig. 13.4 demonstrates how strlen() counts the number of
characters in My House string.NB: The output shows that the number of characters are 8 because the space between
My and House is also counted as a character.
Table 13.3 below presents some common string manipulation functions supported by
C++.Activity 13.1: Library functions
In groups, review at least two programming languages installed on computers in the
computer lab. Perform the following tasks:
1. Identify at least ten math library functions and use an example to explain how
each function works.
2. Bisangwa took a loan of 400 000 FRW from a local bank at annual interest rate
of 12% . Assuming the loan should be paid in 4 years time, write a C++ program
that makes use of library functions to compute monthly loan rep ayment.13.2.2 User-defined Functions
We create user-defined functions to modularize a program or make it available in
C++ Library for use by other programmers. Creating user-defined functions require
that you declare the function name, return type, and list of arguments. After the
declaration, you can then define the function body by enclosing its statements in {
} braces as follows:Explanation
• In the general syntax, type is the data type to be returned by the function. For example, in our previous examples, we have seen that main() returns int type.
• func_name is the identifier by which it will be possible to call the function. For example, main() with brackets indicates that it is a function.
• arg-list is a list of parameters also known as arguments that serves as placeholders for actual data to be received from another function. Arguments are separated by commas, with each comma-separated list consisting of data type followed by arguments e.g., int a. In our previous examples, main() with empty parenthesis list indicates that it does not receive arguments.
• statements is the function’s body that consists of a block of statements enclosed in { } braces. The statements include local variables, executable statements, and optional return statement. For example, main has the last statement as “return 0”. When a function is called by another function, execution is transferred to the function until the return statement or end of function is encountered. To demonstrate how functions work, the following program calculates the sum of two numbers received from the main function:Fig. 13.5 shows a sample output from the program. Note that the screen does not explicitly show how the function was called.
The following is a brief description about how the above progra m works:
• The execution environment in most cases in an operating system starts by calling
the main () function.
• The main function has three variables sum, x and y that are initialized to 0, 5
and 7 respectively.
• The next statement is referred to as function call that transfers control to a function
named addition. The x and y inside parentheses are called actual arguments
because they hold assigned values 5 and 7.
• The two values of x and y are “sent”, (passed) to a function called addition
through a process known as “parameter passing”. Note that the data type and
order in which the values are received should match that of the function call as
illustrated below:• The control is passed to the addition function, arguments a and b known as formal parameters received from main(), i.e., 5 and 7 are assigned to as a and b follows:
• The two values are summed up and assigned to a variable (sum) in the addition function as follows:
• The statement return sum returns as a value of 12 and transfers control back to the
next statement following the function call in the main function. Note that the return
statement can be a value or an expression that returns a value such as:• Finally, the main function prints the value received from addition function. Note the value has been assigned to total that is specific to main, hence referred to as local variable.
Activity 13.2: User-defined functions
1. Study the code snippet shown below and identify the function’s list of parameters, return type and the value returned by the maximum function:2. Write a complete program in which the maximum function is called flow the
main ();
3. Write a program that computes area of a rectangle in a function called rect_area.
The rectangle then returns the calculated area to the main func tion.13.3 Function declaration
C++ requires that a function be defined before being called by the main () function or any other function. For example, addition function in our previous example comes before main. However, if you do not want to fully implement a function, you can first declare it and implement it later. To declare a function without implementing the body, write the function return type, name and parameter list followed by a semicolon at the end of the statement. The portion of a function that includes only the function name and list of arguments is called a function signature or prototype. For example, the following statement is a sample declaration for a function named maximum that takes 3 parameters.1. Explain the purpose of each of the following statements:
(i) void maximum(int,int,int);
(ii) cout<< maximum(6,7,0);
2. Write a program that receives marks for three subjects: Mathematics, Computer Science and Physics/Economics. The program should pass received parameters to a function called calculator(). Once the calculator() function computes the mean score, the value is returned to a grader() function that determines mean grade as follows:
• 80 - 100 A
• 65 - 79 B
• 50 - 64 C
• Below 50 F13.3.1 Function Return Type and Arguments
We have seen that declaration of a function consists of return type, function name and a list of parameters. The return type and argument list can be of the following type:
• Primary data type – a function can return data types such as int, double, float, char and bool.
• Complex data types - a function can receive or return composite data structures like arrays, records (struct), linked list and string:
• Void type – this is a special type, which means a function does not return any value.
In C++, empty parenthesis also implies that the function takes void argument list.13.3.1.1 Functions with arguments and return type
A function can receive at least one argument and return a single value to the caller.
For example, the following printreport() function takes two parameters of int types,
computes quotient, and returns a value of double type:
double printreport(int x,int y){
return = x/y;
}
13.3.1.2 Functions with no arguments and no return type
The keyword void may be used to specify that a function neither receives arguments nor returns a value. For example, the printreport() function below does not receive arguments and returns void:
void printreport(void) {
int x = 5, y =10;
cout<<”Quotient is”<<x/y;
}13.3.1.3 Functions with arguments and no return type
A function can receive one or more arguments and return nothing. For example, the
following printreport() used void to explicitly declare that the function takes two
arguments but returns void:void printreport(int, int) {
cout<<”Quotient is”<<x/y;
}13.3.1.4 Functions with return type and no arguments
A function that receives nothing can be defined in a manner that it returns a value to the caller. For example, the printreport() function below does not receive arguments but returns void:double printreport(void) {
int x = 5, y =10;
return x/y;
}Activity 13.4: Function return type and arguments
1. Explain what happens if the return type is not explicitly declared, but the argument list is a mixture of types as shown below.caculator(int x, int y, float z){
return(x+y+z)
}2. Modify the calculator program created in Activity 13.5 to include a void function named printGrade that prints Average Mark and grade received from the grader() function
13.3.2 Scope of Variables and Constants
The scope specifies where a variable and a constant can be referenced in a program.
Scope of a variable can be either of global or local scope. Global identifiers can be referenced throughout a program, while local identifiers can only be referenced within the body of a function. Formal parameters are treated as local variables used exactly as if they had been declared in the function body. The following program demonstrates how to use global and local variables.Fig. 13.6 below shows the output after the user keys in a value for degress fahrenheit:
change a variable in a way that is invisible to another function. This sharing can
cause logic errors due to bugs that are very difficult to find.13.3.3 Parameter Passing
Parameter passing serves as the communication mechanism between two functions.
Once a call statement is encountered, the caller function passes actual parameters
to the function being called. For example, the program below ha s a call statement;
z=addition (x,y) that passes actual parameters 5 and 3 to addition function.The output after running the program is shown in Fig. 13.7 below:
In this case, once the values of x and y are passed to addition function, they are assigned to a and b.
Activity 13.5: Parameter passing
1. Write a function named distance that calculates the distance between two points on a cartesian plane (x1, y1) and (x2, y2). All formal parameters and the return value should be of type double.
2. Determine whether the following program segments contain errors. For possible error(s), explain how it can be corrected.Assessment Exercise 13.1
1. Differentiate between definition prototype and function declaration.
2. State five advantages and three disadvantages of using functions.
3. State five common characteristics of a function.
4. Using Math library functions, write the following equation as a C++ expression:
y = ax3 + bx2 + cx +d.
5. Using examples, explain four functions that you can use to manipulate characters and strings.
6. Differentiate between void data type and empty parameter list.
7. Differentiate between global and local identifiers. Explain why it is undesirable to use global variables.
8. Using examples, differentiate between pass-by-value and pass-by-reference as used in structured programming.
9. Janet deposited 400,000 in her savings account. The amount deposited earns interest at 3% annually. Write a program that has a function called calculator that receives deposit and years from main() to calculate amount and accrued interest after n years. Note that interest rate should be global constant of double type.13.4 Recursive Functions
Some problems solved recursively are usually those in which you act on data and then act on the results the same way. Recursion is the process of repeating items in similar manner meaning that a recursive function is a function that calls itself in a similar manner. Such functions are useful in solving problems that are recursive in nature such as factorial, greatest common divisor (GCD) and fibonacci series.Activity 13.6: Recursive functions
1. Using your knowledge in Mathematics, demonstrate how you would compute factorial of integer numbers like 20!
2. Using a tree diagram, demonstrate how you would recursively determine the greatest common divisor (GCD) of two numbers, say, 420 and 42.
To demonstrate how recursive functions work. Let’s consider a mathematical problem
of finding factorial of a non-negative integer n, written as n! In order for the recursion
to terminate, the iterations must eventually converge to a base case such as 1 in n. For
example, 5! is the product of 5 * 4 * 3 * 2 * 1, which terminates at 1 to return 120.
Omitting the base case, or writing the recursion step incorrectly so that it does not
converge on the base case, causes “infinite” recursion analogous to infinite loop in a
looping control structures. The following program implements a recursive function
called factorial.Fig. 13.8 shows a sample output after running the program.
Explanation
1. The execution starts with the main function that prompts the user to type a number.
2. Once the number is entered, the function call factorial(number) in the last cout statement transfers control to the factorial function.
3. The factorial function receives the parameter and assigns it to n.
4. The factorial recursively calls itself in the statement factorial(n-1) until the base value -1 is reached.
5. The iteration stops and results displayed on the screen.
Let us consider another mathematical problem of generating Fibonacci series. In Fibonacci series, the next number is the sum of the previous two Fibonacci numbers as shown below:
0,1,1,2,3,5,8,13,21,…
This fibonacci series can be generated and displayed on th sreen by the following program:Fig 13.9 shows the output screen of the program that prints a fobinacci series of natual
numbers 0 to 12.13.4.1 Recursion vs iteration
• Iteration explicitly uses a repetition structure while recursion achieves repetition through repeated function calls.
• Both iteration and recursion involve a termination test: iteration terminates when the loop–continuation condition fails; recursion terminates when a base case is recognized.
• Iteration with counter-controlled repetition and recursion gradually approach
termination:
• Iteration modifies a counter until the counter assumes a value that makes the loop-continuation condition to fail; recursion produces simpler versions of the original problem until the base case is reached.
• Both iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem during each recursive call in a manner that converges on the base case.
• Unlike iteration, recursive functions can be expensive in terms of processor time and memory space. This is because each recursive call causes another copy of the function to be created.Activity 13.7: Recursive functions
1. Implement a modular program for calculating Fibonacci series for nth term
received from main() function.
2. The greatest common divisors of two natural numbers can be easily determined recursively. Write a program for finding GCD of two natural numbers p and q
using the following function definition:Assessment Exercise 13.2
1. Define the following terms:
(a) Recursion
(b) Recursive function
2. Differentiate between recursion and looping control statement.
3. Paul wrote a program that has factorial recursive function. However, after running the program, it was not terminating.
(a) What type of bug is making the program not to terminate?
(b) Advise Paul on how to eliminate the bug.
5. Explain why it is not advisable to use recursive functions if a problem can be solved using iterations.
6. Using an example, explain how a program would recursively find greatest common divisor of two natural numbers p and q.Unit Test 13
1. Explain the following concepts as used in C++ programming:
(a) Functions
(b) Arguments
(c) Parameter passing
2. Differentiate between library functions and user-defined functions.
3. Demonstrate how you would use library functions to compute volume of a sphere.
4. Helen wrote a modular program for finding the volume of a cube. Though the program was running, the calc_volume function was returning void causing unexpected output in the main function.
(a) What type of bug is making the program return invalid results?
(b) Advise Helen on how to eliminate the bug
5. Explain why parameter passing is an important concept in modular programming.
6. Global sharing of variables is one of the major reason for paradigm shift to object
oriented programming. Explain why.
7. Write a program that uses recursion to output fibonacci series from the first fifty natural numbers.
8. Write a program that reads temperature Celsius in the main function. The parameters is passed a function called calc_cel that returns double to a void function that displays the value of temperature in degrees Fahrenheit.
9. Jack deposits 20,000 FRW in a bank at an interest rate of 10% per annum. At the end of each year, the interest earned is added to the deposit and the new amount becomes the deposit for that year. Write menu-driven program that would be used to track interest over a period of five years.The program should output interest and principal amount accumalated in each year.10. Study and give the output of the following program.