Chapter 2 Function
Chapter 2 Function
Functions
1
Objectives
This chapter aims for the students to
Understand basic concepts and need of function
Declaring and defining a function
Differentiate predefined and user defined functions
Understand parameters and arguments of a function
Understand default arguments and function overload
Understand static and auto variables (global and local
variables)
Calling /invoking function by value and reference parameters
Understand recursive and iterative functions
Chapter2: Functions
2
C++ Functions
● A way to write a program is to first design the method the program
use, and write this method in English – this is what we call algorithm.
● A good plan of attack for designing the algorithm is to break down the
task to be accomplished into a few subtask, decompose subtasks
into smaller subtasks, and so forth.
● This is top-down design or divide and conquer.
● Preserving top-down structure
○ Makes the program easier to understand, easier to change if need
be, and
○ Easier to write, test, debug
● C++ provide facilities to include separate subparts inside of a program
● In other programming languages, it is called subprograms,
procedures, or methods.
● In C++ it is called function
● A function can be defined, either as part of the main program or in a
separate file so that it can be use by several programs
Chapter2: Functions
3
What is a function?
● A construct for grouping statements together to perform a task.
● A function provides a convenient way of packaging a
computational way, so that it can be used as often as required.
● Therefore, a function is a block of code designed to tackle a
specific problem (task). Eg. withdrawal, deposit, loan, sum,
product, etc
Function Basics
● One of the best ways to tackle a problem is to start with the
overall goal, then divide this goal into several smaller tasks. You
should never lose sight of the overall goal, but think also of how
individual pieces can fit together to accomplish such a goal.
● If your program does a lot, break it into several functions. Each
function should do only one primary task.
Chapter2: Functions
4
What is a function cont’d
• Functions allow you to modularize a program by separating
its tasks into self-contained units.
• You’ve used a combination of library functions and your
own functions in almost every program you’ve written.
• There are several motivations for modularizing a program
with functions:
• Software reuse. we do not have to define how to read a line of text from
the keyboard—C++ provides this capability via the getline function of the
<string> header.
• Avoiding code repetition.
• Dividing a program into meaningful functions makes the program easier to
test, debug and maintain.
• To promote software reusability, every function should be
limited to performing a single, well-defined task, and the
name of the function should express that task effectively.
Chapter2: Functions
5
What is a function cont’d
C++ functions generally adhere to the following rules.
● Every function must have a name.
● Function names are made up and assigned by the
programmer following the same rules that apply to naming
variables.
● They must be valid identifiers whose size vary per compilers
● All function names have one set of parenthesis immediately
following them.
● This helps you (and C++ compiler) differentiate them from
variables.
● The body of each function, starting immediately after
parenthesis of the function name, must be enclosed by
braces.
● Functions can be predefined or user defined
● Predefined functions require inclusion of header files
which contain their definition
Chapter2: Functions
6
Predefined functions
• C++ comes with libraries of predefined functions that you can use in your
programs. Example:
• sqrt function is a predefined function that calculates the square
root of a number.
• You can use a function call directly in a cout statement, as in the
following:
cout << "The side of a square with area " << area
<< " is " << sqrt(area); or
cout<<sqrt(9); // which produces 3
sqrt() is defined in the heder file cmath, thus we need to include it:
#include <cmath>
• A few predefined functions are shown (next slide);
• Notice that the absolute value functions abs and labs are in the library with
header file cstdlib, so any program that uses either of these functions must
contain the following directive:
#include <cstdlib>
• Next slide shows sample of predefined functions along with library headers
Chapter2: Functions
7
Chapter2: Functions 8
Random number generator
• Games and simulation programs often require the generation of
random numbers.
• C++ has a predefined function to generate pseudorandom numbers.
• A pseudorandom number is one that appears to be random but is
really determined by a predictable formula.
• For example, here is the formula for a very simple pseudorandom
number generator that specifies the ith random number Ri based
on the previously generated random number Ri-1:
• Ri = (Ri−1 x 7) % 11
• Let’s set the initial “seed,” R0 = 1. The first time we fetch a “random”
number
• we compute R1 with the formula:
• R1 = (R0 x 7) % 11 = (1 x 7) % 11 = 7 % 11 = 7
• The second time we fetch a “random” number we compute R2 with:
• R2 = (R1 x 7) % 11 = (7 x7) % 11 = 49 % 11 = 5
• The third time we fetch a “random” number we compute R3 with:
• R3 = (R2 x 7) % 11 = (5 x 7) % 11 = 35 % 11 = 2
• and so on.
Chapter2: Functions
9
Random number generator
• C++ has a predefined function called rand(), defined in cstdlib header
library, generates random rather pseudorandom numbers between 0
and RAND_MAX
• Every time the calling program is run, the same number is displayed; this is because
srand(1) is used by default
• To vary the random number sequence every time the program is
executed, we can seed the random number generator with the time of
day:
• Call srand(time(0)); before rand() is called
• Invoking the predefined function time(0) returns the number of seconds
that have elapsed since January 1, 1970 on most systems. The time
function requires you to include the ctime library.
#include <cstdlib>
#include <ctime>
...
srand(time(0));
Calling rand() seems more random
• To randomly generate integers 1 to 6, use rand()%+1
Chapter2: Functions
10
User defined functions
Declaring, defining and calling functions
Declaring function (also called function prototype)
● It is an interface that specifies how a function may be used.
● A function declaration tells you all you need to know to write a call
to the function. A function declaration is required to appear in
your code prior to a call to a function whose definition has not yet
appeared. Function declarations are normally placed before the
main part of your program.
● It consists of three entities:
● The function return type. This specifies the type of value the
function returns. Eg. int, char, double, etc
● A function which returns nothing should have a return type void.
● The function name. this is simply a unique identifier
• The function parameters (also called its signature). This is a set of zero or
more typed identifiers used for passing values to and from the function.
• Eg. int withdrawal(float amt);
Chapter2: Functions
11
User defined functions cont’d
int maximum(int x, int y, int z); // function prototype
• This is a function prototype, which describes the maximum function
without revealing its implementation.
• A function prototype is a declaration of a function that tells the compiler
the function’s name, its return type and the types of its parameters.
• This function prototype indicates that the function returns an int, has the
name maximum and requires three int parameters to perform its task.
• The portion of a function prototype that includes the name of the function
and the types of its arguments is called the function signature or simply
the signature.
• The function’s return type is not part of the function signature.
• Notice that the function prototype is the same as the first line of the
corresponding function definition, but ends with a required semicolon.
• Parameter names in function prototypes are optional (they’re ignored by
the compiler), but many programmers use them for documentation
purposes.
• Declaring function parameters of the same type as int x, y instead of int x,
int y is a syntax error—a type is required for each parameter in the
parameter list.
Chapter2: Functions
12
User defined functions cont’d
• Returning Control from a Function to Its Caller
• When a program calls a function, the function performs its task, then
returns control (or a value) to the point where the function was called.
• In a function that does not return a result (i.e., it has a void return type),
control returns when the program reaches the function-ending right brace.
You also can explicitly return control to the caller by executing the
statement
return;
• A function prototype is required unless it is defined before being used.
• When you use a standard library function like sqrt, you do not have
access to the function’s definition, therefore it cannot be defined in your
code before you call the function. Instead, you must include its
corresponding header (<cmath>), which contains the function’s prototype
and definition.
• If a function is defined before it’s called, then its definition also serves as
the function’s prototype, so a separate prototype is unnecessary.
• If a function is called before it’s defined, and that function does not have a
function prototype, a compilation error occurs.
Chapter2: Functions
13
Syntax for function declaration and definition
Chapter2: Functions 14
Functions definition
● A function definition describes how the function
computes the value it returns.
● A function definition consists of two parts:
● Function header (prototype) & function body.
● Function body. The brace of a function contains the
computational steps (statements) that computerize the
function.
● Always provide function prototypes, even though it’s
possible to omit them when functions are defined
before they’re used.
● Providing the prototypes avoids tying the code to the order in
which functions are defined (which can easily change as a
program evolves)
Chapter2: Functions
15
Calling a function
● Using a function involves ‘calling’ it.
● Calling a function means making the instruction of the function to
be executed.
● A function call consists of the function name followed by the call
operator brackets ‘()’, inside which zero or more comma-separated
arguments appear.
● The number and type of arguments should match the number of
function parameters.
● Each argument is an expression whose type should match the type
of the corresponding parameter in the function interface
(prototype).
● When a function call is executed,
○ the arguments are first evaluated and their resulting values are
assigned to the corresponding parameters.
○ The function body is then executed.
○ Finally the return value (if any) is passed to the caller.
Chapter2: Functions
16
Calling a function cont’d
● A function call in C++ is like a detour on a highway.
● Imagine that you are traveling along the “road” of the
primary function called main().
● When you run into a function-calling statement, you
must temporarily leave the main() function and execute
the function that was called.
● After that function finishes (its return statement is
reached), program control returns to main().
● In other words, when you finish a detour, you return to
the “main” route and continue the trip. Control
continues as main() calls other functions
Chapter2: Functions
17
Calling a function cont’d
• A function is invoked by a function call, and when the called
function completes its task, it either returns a result or simply
returns control to the caller.
• An analogy to this program structure is the hierarchical form
of management
Chapter2: Functions
18
Calling a function cont’d
• A boss (similar to the calling function) asks a worker (similar
to a called function) to perform a task and report back (i.e.,
return) the results after completing the task.
• The boss function does not know how the worker function
performs its designated tasks.
• The worker may also call other worker functions, unknown to
the boss.
• This hiding of implementation details promotes good software engineering.
• The boss function divides the responsibilities among the
worker functions, and worker1 acts as a “boss function” to
worker4 and worker5 (previous slide)
• The relationship does not need to be hierarchical, but often it
is, which makes it easier to test, debug, update and maintain
programs.
Chapter2: Functions
19
Lets have another very simple function
example:
#include<iostream>
Using namespace std;
void starLine(); //function prototype
//func
int main()
definition
{ starLine(); //Calling the function with a
void starLine()
name starLine
{
cout<< “Data type Range” << endl;
for(int
starLine();
j=0;j<45;j++)
cout<< “char -128 to 127” <<endl
cout<< “*”;
<< “short -32,768 to 32,767” <<endl
cout<<endl;
<< “ int system dependent” <<endl
}
<< “long -2,147,483,648 to
2,147,483,647” << endl;
starLine();
return 0; }
Chapter2: Functions 20
Given the next program, which function is the
calling function and which is the called function?
#include<iostream>
void nextMsg();
int main()
{
cout<< “Hello!\n”;
nextMsg();
return 0;
void nextMsg() {
}
cout<< “GoodBye!\n”;
return;
}
Chapter2: Functions 21
Function parameters and arguments
● The formal parameters (is used as a kind of blank, or
place holder, to stand in for the argument)
● are list of variables used by the function to perform its
task, and
● the arguments passed to the function during calling of a
function are values sent to the function.
● The arguments of function calling can be using either of
the two supported styles in C++: passing by value or
passing by reference.
Passing by value:
● A value parameter receives a copy of only the value of
the argument passed to it. As a result, if the function
makes any changes to the parameters, this will not
affect the argument. For instance (see next slide)
Chapter2: Functions
22
#.....
int main()
{ int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
return 0;
}
Chapter2: Functions 23
Pass by value
● The single parameter of Foo is a value parameter.
● As far as this function is concerned, num behaves just
like a local variable inside the function.
● When the function is called and x passed to it, num
receives a copy of the value of x.
● As a result, although num is set to 0 by the function, this
does not affect x.
● The program produces the following output:
○ Num = 0
○ x = 10
● Passing arguments in this way, where the function
creates copies of the arguments passed to it is called
passing by value Chapter2: Functions 24
Pass by reference
● A reference parameter, on the other hand,
receives the argument passed to it and
works on it directly. Any change made by
the function to a reference parameter is in
effect directly applied to the argument.
● Passing parameters in this way is called
pass-by-reference
● Taking the same example with pass by
reference (next slide)
Chapter2: Functions 25
#.....
int main()
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
return 0;
}
void Foo(int & num)
{
num = 0;
cout<< “num = ” << num << “ \n”;
}
Chapter2: Functions 26
Pass by reference cont’d
● The parameter of Foo is a reference parameter. Num
will correspond to x for this specific program as it x is
sent by its reference and not its value.
● Any change made on num will be effected to x. Thus,
the program produces the following output:
num = 0
x=0
● Suppose you have pairs of numbers in your program
and you want to be sure that the smaller one always
precedes the larger one.
● To do this, you call a function, order(), which checks two
numbers passed to it by reference and swaps the
originals if the first is larger than the second.
Chapter2: Functions 27
#.......
void order(int &, int &);
int main() {
Chapter2: Functions 29
Global vs local variables
● Everything defined at the program scope level (outside
functions) is said to have a global scope.
○ Eg.
int num1;
void fun1(int num1)
{
//…
}
Chapter2: Functions 32
Scope operator cont’d
Solution???
● Use scope operator ‘::’ which takes a global entity as
argument.
int num1 = 2;//global variable
//…
Chapter2: Functions 38
inline functions cont’d
{ cout<< (x*y*z);
}
//thus the following function definition will be correct
cout<< (x*y*z);
}
Chapter2: Functions 43
Overloaded functions
Chapter2: Functions 45
Overloaded functions cont’d
• N.B: if two or more functions differ only in
their return types, C++ can’t overload them.
• Two or more functions that differ only in their
return types must have different names and
can’t be overloaded
• without using overloading, you have to call the
function as:
int ans = iAbs(weight);//for int arguments
float ans = fAbs(weight);//for float arguments
• But with overloading, the above code can be
used as shown (next slide)
Chapter2: Functions
46
int abs ( int i ); int Abs(int i)
float Abs ( float x ); {
int main ( ) if(i<0)
return i*-1;
{ else
… return I;
ians = Abs(i);//calling abs }
Chapter2: Functions
47
Recursion
○ factorial of 0 is 1
}
Chapter2: Functions 48
For n set to 4, the following figure shows the recursive
call:
Factorial ( 4 )
24
4 * Factorial ( 3 )
6
3 * Factorial ( 2 )
2
2 * Factorial ( 1 )
1 1
Chapter2: Functions 49
Chapter2: Functions 50
Recursion cont’d
Chapter2: Functions 51
Recursion cont’d
• The three necessary components in a recursive method
are
A test to stop or continue the recursion
An base case or end case that terminates the
recursion
A recursive call(s) that continues the recursion
• let us implement two more mathematical
functions using recursion
• e.g the following function computes the sum of the first
N positive integers 1,2,…,N.
• Notice how the function includes the three necessary
components of a recursive method (next slide)
Chapter2: Functions 52
Recursion cont’d
int sum(int N) {
if(N==1)
return 1;
else
return N+sum(N-1);
}
• The last method computes the exponentiation A n where A is a real number and N is
a positive integer. This time, we have to pass two arguments. A and N. the value of
A will not change in the calls, but the value of N is decremented after each recursive
call.
float expo(float A, int N) {
if(N==1)
return A;
else
return A * expo(A,N-1);
}
Chapter2: Functions
53
Recursion cont’d
Chapter2: Functions 57
End of Chapter 2
Chapter2: Functions 58