0% found this document useful (0 votes)
74 views102 pages

Unit 5 (C++) - Function

The document discusses functions in C++. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined/library functions and user-defined functions. Predefined functions are included from standard libraries while user-defined functions are created by programmers. Functions make programs more modular and reusable.

Uploaded by

abdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views102 pages

Unit 5 (C++) - Function

The document discusses functions in C++. It defines a function as a block of code that performs a specific task. There are two types of functions: predefined/library functions and user-defined functions. Predefined functions are included from standard libraries while user-defined functions are created by programmers. Functions make programs more modular and reusable.

Uploaded by

abdi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 102

UNIT FIVE

FUNCTIONS

1
Function
 Computer programs that solve real-world problems are
usually much larger than the simple programs.
 To design, implement and maintain larger programs it is
necessary to break them down into smaller, more
manageable pieces or modules.
 Dividing the problem into parts and building the solution
from simpler parts is a key concept in problem solving and
programming.
 In C++ we can subdivide the functional features of a
program into blocks of code known as functions.
 In effect these are subprograms that can be used:
 To avoid the repetition of similar code and
 Allow complicated tasks to be broken down into parts, making the
program modular. 2
 Until now you have encountered programs where all the
code (statements) has been written inside a single function
called main().
 Every executable C++ program has at least this function.
 Function is a block of instructions that is executed when
it is called from some other point of the program.
 Function is a self-contained routines within a larger
program that carry out specific tasks.
 Function is one entity in programming which have a set
of command to carry out specific task
 We can call these function every time we need (in
programming sequences) – reusable
 Functions are often called modules.
 They are like miniature programs; you can put them
together to form a larger program.
3
Why we need function?
 To organize code in program by avoiding
repetition of the code and make the program more
readable because it reduces the complexity of the
function main
 To break down the program in to more
manageable parts
 Easier to maintain the code
 To repeat the same process over and over in a
program (reusable of the code).
 To call the function many times but appears in the
code once.
4
Pre-defined and User-defined Functions
• C++ functions can be divided into 2 categories: Pre-
defined and User-defined functions.
1) Pre-defined (standard function) / library function
 Which is the definitions have been written and it is ready
to be used.
 User needs to include pre-defined header file (i.e. math.h,
time.h, and etc).
 Some of the predefined mathematical functions are
pow(x, y), sqrt(x), and floor(x).
 The power function, pow(x, y), calculates xy; that is, the
value of pow(x, y)= xy.
 For example, pow(2, 3)= 23= 8.0 and pow(2.5, 3)= 2.53 =
15.625.
.
5
 Because the value of pow(x, y) is of type double, we say
that the function pow is of type double or that the
function pow returns a value of type double.
 Moreover, x and y are called the parameters (or
arguments) of the function pow.
 Function pow has two parameters.
 The square root function, sqrt(x), calculates the non
negative square root of x for x >= 0.0.
 For example, sqrt(25) is 5.
 The function sqrt is of type double and has only one
parameter.

6
 The floor function, floor(x), calculates the largest whole
number that is less than or equal to x.
 For example, floor(48.79) is 48.0.
 The function floor is of type double and has only one
parameter.
 In C++, predefined functions are organized into separate
libraries.
 For example, the header file iostream.h contains I/O
functions, and the header file math.h contains math
functions.
 Look at the following C++ program to implement some of
pow and abs predefined functions.

7
#include <iostream.h>
#include <math.h>
#include <ctype.h>
int main()
{
int x;
double u, v;
cout << " Uppercase of a is "<< static_cast<char>(toupper('a'))<< endl;
u = 4;
v = 3;
cout << "The power result is :"<< pow(u, v) << endl;
cout <<“The result of the power is:"<< pow(5, 4) << endl;
u = u + pow(3, 3);
cout <<"The result of U is:"<< u << endl;
x = -15;
cout <<"Absolute Value of the number is:"<< abs(x) << endl;
return 0;
} 8
 The following are some of the Standard Math Library in
C++ programming language:
 fabs : absolute value of floating point number
 floor : largest integral value not greater than x
 ceil : smallest integral value not less than x
 fmod : floating-point remainder function
 log : logaritma
 pow : Raise a number by a power.
 sin : The sine of an integer.
 sqrt : Square root of a number.
 tan : Tangent.
 tanh : Hyperbolic tangent.
9
2) User-defined function
 Function that had been created by the programmers or
users.
 This is because C++ allows programmers to define their
own functions to implement a particular task.
 This functions need to be declared and defined by the
programmer or user.
 A function is a block of instructions that is executed
when it is called from some other point of the program.
 One of this function is a user-defined function.
 The syntax of user defined function is as follows

type name(argument1, argument 2,-------)


{
statement;
} 10
 Where:
a) type is the type of data returned by the function.
b) name is the name by which it will be possible to call the
function.
c) arguments (as many as wanted can be specified).
 Each argument consists of a type of data followed by its
identifier, like in a variable declaration (for example, int
x) and which acts within the function like any other
variable.
 They allow passing parameters to the function when it is
called.
 The different parameters are separated by comma.
d) statement is the function’s body.
 It can be a single instruction or a block of instructions
and it must be delimited by curly brackets { }. 11
Example 1
//Program to define a function by the name addition.
#include<iostream.h>
int addition (int a, int b){
int r;
r= a+b;
return (r);
}
int main (){
int z;
z= addition(5,3);
cout<<"The result is:"<<z;
return 0;
}
We can see how the main function begins by declaring the
variable z of type int. Right after that we see a call to addition
function.

12
 We will be able to see the similarity between the structure of the
call to the function and the definition of the function itself in the
code lines above:
int addition (int a, int b)

z= addition ( 5 , 3);
 The parameters have a clear correspondence.
 Within the main function we called to addition passing two
values: 5 and 3 that correspond to the int a and int b parameters
declared for the function addition.
 At the moment at which the function is called from main, control
is lost by main and passed to function addition.
 The value of both parameters passed in the call (5 and 3) are
copied to the local variables int a and int b within the function.

13
 Function addition declares a new variable (int r) and by means of
the expression r=a + b;, it assigns to the result of a plus b.
 Because the passed parameters for a and b are 5 and 3 respectively,
the result is 8.
 The line of code return (r), finalizes function addition, and returns
the control back to the function that called it (main() following the
program from the same point at which it was interrupted by the call
to addition.
 But additionally, return was called with the content of variable r
(return (r); ), which at that moment was 8, so this value is said to
be returned by the function.
int addition (int a, int b)

z= addition( 5 , 3 );

8
14
 The value returned by a function is the value given to
the function when it is evaluated.
 Therefore, z will store the value returned by addition (5,
3), that is 8.
 To explain it another way, you can imagine that the call
to a function (addition (5,3)) is literally replaced by the
value it returns (8).
 The line of code: cout<<“The result is “<<z; produces
the printing of the result on the screen.

15
Functions with no parameters
 Functions with no parameters are of limited use. Usually they will
not return a value but carry out some operation.
 For example consider the following function which skips three lines
on output.
void skipthree(void)
// skips three lines on output
{
cout << endl << endl << endl;
}
Note that the function-type has been given as void, this tells the
compiler that this function does not return any value.
Because the function does not take any parameters the parameter-
list is empty, this is indicated by the void parameter-list.

16
 No local variables are required by this function and the function
implementation only requires the sending of three successive end
of line characters to the output stream cout.
 Note the introductory comment that describes what the function
does.
 All functions should include this information as minimal comment.
 Since this function does not return a value it cannot be used in an
expression and is called by treating it as a statement as follows:

skipthree();
 See the following simple C++ program to implement functions
with no parameter or return value:

17
Example
#include <iostream.h>
#include<conio.h>
void skipthree(void)
// Function to skip three lines
{
cout << endl << endl << endl;
}
void main() {
clrscr();
cout << "Title Line 1";
skipthree();
cout << "Title Line 2";
} 18
 However this has disadvantages, namely:
1.The main program tends to convey much more information
of use in understanding the program than do individual
functions. So it is better if the main program comes first.
 However this means that the compiler meets the call of a
function before it meets the definition of the function.
2. If using functions from a library of functions then the
main program is linked with the pre-compiled object code
of the functions.
 Thus while compiling the main program on its own the
compiler has no knowledge of the function definitions.
 What is the solution for this two problem?
 The way round both the problems above is to use Function
prototypes. 19
Function Prototypes
 A function prototype supplies information about the return
type of a function, name of function to be called and the
types of its parameters.
 It is placed before the main program that uses the function.
 But full function definition is then placed after the main
program or may be contained in a separate file that is
compiled separately and linked to the main program later.
 The function prototype is merely a copy of the function
heading.
 The function prototype is a statement, which means it ends
with a semicolon.
 It consists of the function's return type, name, and
parameter list.
 The parameter list is a list of all the parameters and their
types, separated by commas. 20
 The function prototype and the function definition must agree
exactly about the return type, the name, and the parameter list.
• If they do not agree, you will get a compile-time error.
• Note, however, that the function prototype does not need to contain
the names of the parameters, just their types.
• A prototype that looks like this is perfectly legal:
long Area(int, int);
 This prototype declares a function named Area() that returns a long
and that has two parameters, both integers.
 Although this is legal, it is not a good idea.
 Adding parameter names makes your prototype clearer.
 The same function with named parameters might belong long
Area(int length, int width);
 It is now obvious what this function does and what the parameters
are.

21
General syntax of function prototypes

return_type function_name( type PName1, type PName2,…..);

Where,PName1 and PNme2 is parameter 1 and parameter 2


respectively.
The prototype function is identical to the header of
a function definition, except:
It does not include a statement for the function.
That means that it does not include the body with all
the instructions that are usually enclose within curly
brackets {}.

22
Function Prototype Examples
long FindArea(long length, long width); // returns long, has two
parameters
void PrintMessage(int messageNumber); // returns void, has one
parameter
int GetChoice(); // returns int, has no parameters
BadFunction(); // returns int, has no parameters
Void getName(void); //No return value (b/c no parameters)
Every function has a return type. If one is not explicitly designated,
the return type will be int.
Be sure to give every function an explicit return type.
If a function does not return a value, its return type will be void.
The following example is a C++ program to implement the function
prototype for the function skipthree is: void skipthree(void);
which would be included in the program file as follows:

23
Function Prototype Example 1
#include <iostream.h>
void skipthree(void); // function prototype or declaration
//Function has to be declared before the main function
void main() {
int x ;
float y;
cout << "Title Line 1";
skipthree();
cout << "Title Line 2";
}
// Here is the function definition after the main program
void skipthree(void)
// Function to skip three lines
{
cout << endl << endl << endl;
} 24
Function Prototype Example 2
//Program to implement prototyping
#include<iostream.h>
#include<conio.h>
void odd (int a);
void even (int a);
int main (){
clrscr();
int n;
do {
cout<<"Enter a number: ( 0 to exit )";
cin>>n;
odd (n);
}
while (n!=0);
return 0;
}
25
void odd (int a) {
if((a%2)!=0) {
cout<<"The number n is odd. \n";
}
else {
even(a);
}
}
void even(int a) {
if((a%2)==0) {
cout<<"The number n is even. \n";
}
else {
odd(a);
}
} 26
 In the above example, the prototyping of at least one of
the two functions is necessary.
 The first things that we see are the prototypes of
functions odd and even:
void odd (int a);
void even (int a);
that allows these functions to be used before they are
completely defined, for example, in main, which now is
located in a more logical space: the beginning of the
program’s code.
 Nevertheless, the specific reason why this program needs
at least one of the functions prototyped is because in odd
there is a call to even and in even there is a call to odd.
27
 If none of the two functions had been previously declared,
an error would have happened, since either odd would not
be visible from even (because it has not still been
declared), or even would not be visible from odd.
 Functions that a programmer writes will generally
require a prototype.
 Just like a blue print, the prototype tells the compiler:
 What the function will return,
 What the function will be called, and
 As well as what parameters the function can be passed.

28
Function Definition and Calls
 Each function has its own name, and when that name is encountered
in a program (the function call), execution of the program branches
to the body of that function.
 After the last statement of the function has been processed (the return
statement), execution resumes on the next line after the call to the
function.
 Functions consist of a header and a body.
1) The header includes the name of the function and tells us the
compiler:
 What type of data it expects to receive (the parameters) and
 Type of data it will return (return value type) to the calling function.
2) The body of the function contains the instructions to be executed.
 If the function returns a value, it will end with a return statement.

29
Syntax of Function Definition
return-value-type function-name (parameter-list )
{
declaration of local variables ;
statements ;
Body of the
return return-value ; Function
}
 The syntax is very similar to that of the main program, which is also a
function.
 main() has no parameters and returns the integer 0 if the program
executes correctly. Hence the return value type of the main() function is
int.
int main() {
declarations ;
statements ;
return 0;
}

30
 Where
a) return value type the type of data it will return (return value type)
to the calling function or program.
 The functionType is also called the data type or the return type of
the value-returning function.
 If the function does not return a value then the function-type must
be void.
b) function-name- the name by which it will be possible to call the
function.
c) The parameter-list lists the formal parameters of the function
together with their types.
d) Local Variable declaration- are definitions of variables that are
used in the function-implementation.
 These variables have no meaning outside the function.

31
f) Statements- are C++ executable statements in the
body of the function.
 It can be a single instruction or a block of
instruction.
g) return return-value- specifies that the value
stored in the function variable should be passed
back to the calling function.
 Both the local variable declaration, statements
and return return value part of the user defined
function is delimited by curly braces and usually
called body of the function.

32
Function definition Example 1

Type name Parameter list


int rectarea(int height, int width) {
int area;
area= height * width; Body of the
function
return area;
} Body of the
function
Activity
1.Define a function that calculates the Area of a Circle and Volume of
a Box.
2.Define a function that prints your first and last name in a separate
line but a function prints the name after one blank line and does not
return the name. 33
Example of function definition, declaration and call
 Let us first look at an example of program written entirely in the
function main() and then we will modify it to use an additional
function call.
 We illustrate this with a program to calculate the factorial (n!) of an
integer number (n) using a for loop to compute:
n! = 1 · 2 · 3 . . . (n − 2) · (n − 1) · n
// Program to calculate factorial of a number
#include <iostream.h>
int main()
{
int number=0, factorial=1;
// User input must be an integer number between 1 and 10

34
While ((number<1) || (number>10)) {
cout << "Enter integer number (1-10) = ";
cin >>number;
}
// Calculate the factorial with a FOR loop
for(int i=1; i<=number; i++)
{
factorial = factorial*i;
}
// Output result
cout << "Factorial = " << factorial << endl;
return 0;
}

35
 Even though the program is very short, the code to
calculate the factorial is best placed inside a function since
it is likely to be executed many times in the same program
or in different programs (e.g., calculating the factorials of
many different numbers, computing binomial coefficients
and permutations and combinations). Look the following
C++ program:
// FunctionFactorial
// Program to calculate factorial of a number with function call
#include <iostream.h>
// Function declaration (prototype)
int Factorial(int M);
int main() {
int number=0, result;
// User input must be an integer number between 1 and 10
While ((number<1) || (number>10)) {
cout <<"Enter Integer number = "; 36
cin >> number;
}
// Function call and assignment of return value to result
result = Factorial(number);
//Output result
cout << "Factorial = " << result << endl;
return 0;
}
// Function definition (header and body)
// An integer, M, is passed from caller function.
int Factorial(int M) {
int factorial=1;
// Calculate the factorial with a FOR loop
for(int i=1; i<=M; i++) {
factorial = factorial*i;
}
return factorial; // This value is returned to caller
} 37
• Three modifications have been made to the above program
to incorporate a function.
1. The declaration of the function above the main program.
 The declaration (also known as the prototype) tells the
compiler about the function and the type of data it requires
and will return on completion.
2. The function call in the main body of the program
determines when to branch to the function and how to
return the value of the data computed back to the main
program.
3. The definition of the function below the main program.
 The definition consists of :
i) a header which specifies how the function will interface
with the main program, and
ii)a body, which lists the statements to be executed when the
function is called. 38
 Before a function can be used it must be declared (0),
usually at the top of the program file.
 When the function name is encountered (function
called) in the main body of the program (1), execution
branches to the body of the function definition (2).
 Copies of the values of function arguments are stored in
the memory locations allocated to the parameters.
 The statements of the function are then executed (3) up
to the first return statement when control returns to the
main body (4).
 Any value returned by the function is stored by an
assignment statement.
 Execution in the main body is resumed immediately
after the function call (5). 39
40
1. Function header and body
 The function is defined below the body of main(). The
header in this example:
int Factorial(int M)
 This indicates that the Factorial() function expects to be
passed an integer value (the parameter type) from the
main body of the program and that the value passed will
be stored locally in a variable named M (the formal
parameter name).
 The return value type of the function is also int in this
example, indicating that at the end of executing the body
of the function, an integer value will be returned to the
statement in which the function was called.
 Functions that do not return a value have return value
type void.
41
 The body of the function computes the factorial of a
number in exactly the same way as in the example with
only a main() function.
 The execution of the function terminates with a return
statement :
return factorial;
which specifies that the value stored in the function
variable factorial should be passed back to the calling
function.
 Note: Strictly speaking, it’s not always essential to
declare a function before it is used, as long as the
compiler encounters the function’s definition before the
function is used.

42
2. Function Declaration
 Every function should be declared before it is used.
 The declaration tells the compiler the name, return value type and
parameter types of the function.
 In this example the declaration:
int Factorial(int M);
tells the compiler that the program passes the value of an integer to the
function and that the return value must be assigned to an integer
variable.
 The declaration of a function is called its prototype, which means the
“first” time the function is identified to your program.
 The function prototype and the function definition must agree
exactly about the return value type, function name and the
parameter types.
 The function prototype is usually a copy of the function header
followed by a semicolon to make it a declaration and placed before
the main program in the program file.
43
3. Function call and execution
 The function definition is entirely passive. By itself it does nothing
unless instructed to execute.
 This is done by a statement in the main program called the
function call. For example the statement:
result = Factorial(number);
calls the function Factorial() and passes a copy of the value stored
in the variable, number.
 When the function is called, computer memory is allocated for the
parameter, M, and the value passed is copied to this memory
location.
 Memory is also allocated to the (local) variables factorial and i.
 The statements of the function are then executed and assign a
value to the variable factorial.

44
 The return statement passes this value back to the calling
function.
 The memory allocated to the parameters and local variables is
then destroyed.
 The value returned is assigned to the variable on the left-hand side,
result, in the expression used to call the function.
 The net effect of executing the function in our example is that the
variable result has been assigned the value of the factorial of
number.
 A function can be called any number of times from the same or
different parts of the program.
 It can be called with different parameter values (though they must
be of the correct type).
 For example the following fragment of code can be used to print
out the factorials of the first 10 integers:
45
for(int i=1; i<=10; i++) {
result = Factorial(i);
cout << i << "! = " << result << endl;
}
4. Function arguments
The names of variables in the statement calling the function will
not in general be the same as the names in the function definition,
although they must be of the same type.
We often distinguish between the formal parameters in the
function definition (e.g. M) and the actual parameters for the values
of the variables passed to the function (e.g. number in the example
above) when it is called.

46
 Function arguments (actual parameters) can include
constants and mathematical expressions.
 For example the following statement assigns the value
24 to the variable result.
result = Factorial(4);
 The function arguments can also be functions that
return an appropriate value (for example
Factorial(Factorial(4)), although this concise style
makes the code harder to read and debug.

47
Example 1
•The following example of using parameters and locally
defined variables within a function.
#include <iostream.h>
float Convert(float);
int main()
{
float TempFer;
float TempCel;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> TempFer;
TempCel = Convert(TempFer);
cout << "\n The temperature in Celsius: "<< TempCel << endl;
return 0;
}
48
float Convert(float TempFer)
{
float TempCel;
TempCel = ((TempFer - 32) * 5) / 9;
return TempCel;
}
In the above program, two float variables are declared, one to
hold the temperature in Fahrenheit and one to hold the
temperature in degrees Celsius.
The user is prompted to enter a Fahrenheit temperature and that
value is passed to the function Convert().
•Execution jumps to the third line of the function Convert() on
line 15, where a local variable, also named TempCel, is declared.

49
 Note that this local variable is not the same as the variable
TempCel on line 6 of in the main function.
 This variable exists only within the function Convert().
 The value passed as a parameter, TempFer, is also just a local
copy of the variable passed in by main().
 This function could have named the parameter FerTemp and
the local variable CelTemp, and the program would work
equally well.
 The local function variable TempCel is assigned the value that
results from subtracting 32 from the parameter TempFer,
multiplying by 5, and then dividing by 9.
 This value is then returned as the return value of the function,
and on line 9 it is assigned to the variable TempCel in the main()
function.
 The value is printed on line 10 of in the main function.

50
Exercise
1. Write C++ program to calculate area of rectangle, area of
triangle and area of the circle by defining the necessary
functions to perform the required task when it is called.
2. Write C++ program that computes to convert temperature
in degree celiecius to temperature in degree Fahrenheit
using function
3. Write C++ program to calculate sum and average of two
numbers by defining and declaring functions.
4. Determine the output of the following C++ program
// Example using subtraction function
#include<iostream.h>
#include<conio.h>
int subtraction(int a, int b);
int main (){
51
clrscr ();
int x=5, y=3, z;
z=subtraction(7, 2);
cout<<"The first result is "<<z<<"\n";
cout<<"The second result is "<<subtraction (7,2)<<"\n";
cout<<"The third result is "<<subtraction (x, y)<<"\n";
z= 4 + subtraction (x, y);
cout<<"The fourth result is "<<z<<"\n";
getch ();
return 0;
}
int subtraction(int a, int b){
int r;
r=a-b;
return (r);
}
52
Scope of the Variables (Local OR Global)
 The scope of variables declared with in a function or any other
block of instructions is only their own function or their own
block of instructions and can not be used outside of them.
 In the following example (see slide 57 and 58), it had been
impossible to use the variables a, b or r directly in function main
since they were local variables to function addition.
 It is also impossible to use the variable z directly within function
addition, since this was a local variable to the function main.
 Therefore, the scope of local variable is limited to the same
nesting level in which they are declared.
 Nevertheless you can also declare global variables that are visible
from any point of the code, inside and outside any function.

53
Local Variables and Global Variables
Here is the short difference between local and global
variables

Local Variables Global Variables

1 Variables declared in a Variables declared


function (or any functions) are before/outside main() are
local to the function. global variables

2 Variables declared in main() They are known throughout


are local to main() the program

54
 Variables defined outside of any function have global scope
and thus are available from any function in the program,
including main().
 Local variables with the same name as global variables do not
change the global variables.
 A local variable with the same name as a global variable
hides the global variable, however.
 If a function has a variable with the same name as a global
variable, the name refers to the local variable--not the global--
when used within the function.
 The following program demonstrates global variables that any
of the function from the outside can access and local
variables that is visible only to the function which is defined.

55
#include <iostream.h>
#include <conio.h>
void myFunction(); // Prototype or Function Declaration
int x = 5, y = 7; // Global Variables
int main() {
clrscr ();
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n\n";
myFunction();
cout << "Back from myFunction!\n\n";
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n";
return 0;
}
56
void myFunction() //Function Definition
{
int y = 10;
cout << "x from myFunction: " << x << "\n";
cout << "y from myFunction: " << y << "\n\n";
}
This simple program illustrates, on line 1, two global variables,
x and y, are declared.
The global variable x is initialized with the value 5, and the
global variable y is initialized with the value 7.
On lines 4 and 5 in the function main(), these values are printed
to the screen.
Note that the function main() defines neither variable; because
they are global, they are already available to main().

57
 When myFunction() is called on line 6, program execution
passes to line 12, and a local variable, y, is defined and
initialized with the value 10.
 On line 15, myFunction() prints the value of the variable x, and
the global variable x is used, just as it was in main().
 On line 16, however, when the variable name y is used, the
local variable y is used, hiding the global variable with the
same name.
 The function call ends, and control returns to main(), which
again prints the values in the global variables.
 Note that the global variable y was totally unaffected by the
value assigned to myFunction()'s local y variable.

58
Note
 In C++, global variables are legal, but they are almost never used.
 C++ grew out of C, and in C global variables are a dangerous but
necessary tool.
 They are necessary because there are times when the programmer
needs to make data available to many functions and he does not
want to pass that data as a parameter from function to function.
 Global’s are dangerous because they are shared data, and one
function can change a global variable in a way that is invisible to
another function.
 This can and does create bugs that are very difficult to find.

59
More on Local Variables

 Variables declared within the function are said to have "local


scope."
 That means, that they are visible and usable only within the
function in which they are defined.
 In fact, in C++ you can define variables anywhere within the
function, not just at its top.
 The scope of the variable is the block in which it is defined.
 Thus, if you define a variable inside a set of braces within
the function, that variable is available only within that block.
 The following program illustrates the variables in the block
which is defined.

60
// scoped variables within a block
#include <iostream.h>
#include <conio.h>
void myFunc();
int main()
{
int x = 5;
cout << "\n In main x is: " << x;
myFunc();
cout << "\n Back in main, x is: " << x;
return 0;
}
61
void myFunc() {
int x = 8;
cout << "\n In myFunc, local x: " << x << endl;
{
cout << "\n In block in myFunc, x is: " << x;
int x = 9;
cout << "\n Very local x: " << x;
}
cout << "\n Out of block, in myFunc, x: " << x << endl;
}
 This program begins with the initialization of a local
variable, x, on line 7, in main().
The printout on line 8 verifies that x was initialized with the
value 5.
MyFunc() is called, and a local variable, also named x, is
initialized with the value 8 on line 14. 62
 Its value is printed on line 15.
 A block is started on line 16, and the variable x from the
function is printed again on line 17.
 A new variable also named x, but local to the block, is
created on line 18 and initialized with the value 9.
 The value of the newest variable x is printed on line 19.
 The local block ends on line 20, and the variable created
on line 18 goes "out of scope" and is no longer visible.
 When x is printed on line 21, it is the x that was declared
on line 14.
 This x was unaffected by the x that was defined on line
18; its value is still 8.
 On line 22, MyFunc() goes out of scope, and its local
variable x becomes unavailable. 63
 Execution returns to line 9, and the value of the local
variable x, which was created on line 7, is printed.
 It was unaffected by either of the variables defined in
MyFunc().
Exercise
1.Write C++ program to perform multiplication and division
of two numbers by defining your own function such as
mul and div to implement local and global variables and
also use variables visible to only within the block.

64
Passing Values to Functions

 There are two ways to pass values to functions.

1)Arguments Passed by Value


2)Arguments Passed by Reference

65
1. Arguments Passed by Value
 When calling a function with parameters, what we have
passed to the function were values but never the
specified variables themselves.
 In the passing by value way of passing parameters, a copy
of the variable is made and passed to the function.
 Changes to that copy do not affect the original variable’s
value in the calling function.
 This prevents the accidental corrupting of variables by
functions and so is often the preferred method for
developing correct and reliable software systems.
 One disadvantage of passing by value however, is that
only a single value can be returned to the caller.

66
Example
The following example demonstrates arguments passed by value.
//Program to implement arguments passed by value
#include<iostream.h>
#include<conio.h>
int addition(int a, int b);
int main (){
clrscr ();
int x=5, y=3, z;
z=addition(x, y);
cout<<"The first result is "<<z<<"\n";
cout<<"The second result is "<<addition (7,2)<<"\n";
cout<<"The third result is "<<addition(x, y)<<"\n";
z= 4 + addition (x, y);

67
cout<<"The fourth result is "<<z<<"\n";
getch ();
return 0;
}
int addition(int a, int b){
int r;
r=a+b;
return (r);
}
For example, suppose that we called a function addition
using the following code:
int x= 5, y=3, z;
z = addition(x, y);
What we did in this case was to call function addition
passing the value of x and y, that means 5 and 3 respectively,
not the variables themselves. 68
int addition (int a, int b)

5 3
z= addition ( x, y);
This way, when function addition is being called the value
of its variables a and b becomes 5 and 3 respectively, but any
modification of a or b within the function addition will not
affect the values of x and y outside it, because variable x and
y were not passed themselves to the function, only their
values.
Exercise
1. Write C++ program to calculate volume of the box to
implement argument passed by value when a function is
called by defining the necessary function.
69
2. Arguments Passed by Reference
 If the function has to modify the value of an argument or
has to return more than one value, then another method is
required, passing by reference.
 An alternative uses passing by reference in which the
function is told where in memory the data is stored (i.e., the
function is passed the memory address of the variables).
 In passing the address of the variable we allow the function
to not only read the value stored but also to change it.
 Here’s an analogy. When you tell a friend about a webpage
on the course C++, you can either print out a copy of the
webpage for them; or you can send them the URL of the
webpage (i.e., URL is address of the webpage).
 Giving them the copy is ‘pass by value’; giving them the
URL is ‘pass by reference’.
70
 When you ‘pass by value’, they can manipulate their copy of
the page, and their manipulations have no effect on the
original page.
 When you ‘pass by reference’, they will be able to edit the
contents of the webpage.
Example
//Program to implement Passing parameters by reference
#include<iostream.h>
#include<conio.h>
void duplicate(int &a, int &b, int &c);
int main() {
clrscr();
int x=1, y=3, z=7;
duplicate(x, y, z);
cout<<"x= "<<x<<", y="<<y<<" , z= "<<z; 71
return 0;
}
void duplicate(int &a, int &b, int &c) {
a*=2; What is the output of this
b*=2; program?
c*=2;
}
The first thing that should call your attention is that in the
declaration of duplicate the type of each argument was
followed by an ampersand sign (&), that serves to specify that
the variable has to be passed by reference instead of by value,
as usual.
When passing a variable by reference we are passing the
variable itself and any modification that we do to that
parameter within the function will have effect in the passed
variable outside it. 72
void duplicate(int &a, int &b, int &c)
x y z
duplicate ( x , y , z );
To express it in another way, we have associated a, b and c
with the parameters used when calling the function (x, y
and z) and any change that we do on a within the function
will affect the value of x outside.
Any change that we do on b will affect y, and the same
with c and z.
That was why our program’s output, that shows the values
stored in x, y and z after the call to duplicate, shows the
values of the three variables of main doubled.
If when declaring the following function:
void duplicate(int &a, int &b, int &c) we had declared
73
it thus:
void duplicate(int a, int b, int c)
That is, without the ampersand (&) signs, we would have
not passed the variables by reference, but their values, and
therefore, the output on the screen for our program would
have been the values of x, y and z without having been
modified.
Note: This type of declaration “by reference” using the
ampersand (&) sign is exclusive of C++. In C language we
would had to use pointers to do something equivalent.
Passing by reference is an effective way to allow a
function to return more than one single value.
For example, here is a function that returns the previous
and next numbers of the first parameter passed. 74
//Passing by parameters for more than one returning value
#include<iostream.h>
#include<conio.h>
void prevnext (int x, int &prev, int &next);
int main () {
clrscr (); What is the output of
int x=100, y, z; this program?
prevnext (x, y, z);
cout<<"Previous = "<<y<<" , Next= "<<z;
return 0;
}
void prevnext (int x, int &prev, int &next)
{
prev= x-1;
next= x+1;
} 75
 Another simple example of passing by reference having function
prototype and definition is given below for a function that swaps
the values of two variables in the calling function’s data by
reading and writing to the memory locations of these variables.
 Note that the parameters are mentioned only by name in the
function call. This appears to be the same as calling by value.
 The function header and prototype, however, must use the &
symbol by the variable name to indicate that the call is by
reference and that the function can change the variable values.
// Program to sort two numbers using call by reference.
// Smallest number is output first.
#include <iostream.h>
#include <conio.h>
// Function prototype for call by reference
void swap(float &x, float &y);
int main() {
clrscr ();
float a, b; 76
cout << "Enter 2 numbers: " << endl;
cin >> a >> b;
if(a>b)
swap(a,b);
// Variable a contains value of smallest number
cout <<"The Sorted numbers are: "<< a << " " << b;
return 0;
}
// A function definition for call by reference
// The variables x and y will have their values changed.
void swap(float &x, float &y)
// Swaps x and y data of calling function
{
float temp;
temp = x;
x = y;
y = temp;
} 77
Return Values
 Functions return a value or return void.
 Void is a signal to the compiler that no value will be
returned.
 To return a value from a function, write the keyword
return followed by the value you want to return.
 The value might itself be an expression that returns a
value. Let see the following examples:
return 5;
return (x > 5);
return (MyFunction());
 These are all legal return statements, assuming that the
function MyFunction() itself returns a value.
 The value in the second statement, return (x > 5), will be
zero if x is not greater than 5, or it will be 1.
78
 What is returned is the value of the expression, 0 (false)
or 1 (true), not the value of x.
 When the return keyword is encountered, the expression
following return is returned as the value of the
function.
 Program execution returns immediately to the calling
function, and any statements following the return are
not executed.
 It is legal to have more than one return statement in a
single function.
 Let’s see the following C++ program to demonstrate a
function having more than one return statements.

79
//Program to demonstrate multiple return statement
#include <iostream.h>
#include <conio.h>
int Doubler(int AmountToDouble);
int main()
{
clrscr ();
int result = 0;
int input;
cout<<"Enter a number between 0 and 10,000 to double:";
cin>>input;
cout<<"\n Before doubler is called... ";
cout<<"\n input: " <<input<< " doubled: " <<result<< "\n";
80
result = Doubler(input);
cout << "\nBack from Doubler...\n";
cout << "\n input: "<< input<<" doubled: " <<result << "\n";
return 0;
}
int Doubler(int original)
{
if (original <= 10000)
return original * 2;
else
return -1;
cout << "You can't get here!\n";
}
 A number is requested on lines 10 and 11, and printed on
line 13, along with the local variable result.
81
 The function Doubler() is called on line 14, and the input
value is passed as a parameter.
 The result will be assigned to the local variable result,
and the values will be reprinted on lines 15 and 16.
 On line 21, in the function Doubler(), the parameter is
tested to see whether it is greater than 10,000.
 If it is not, the function returns twice the original number.
 If it is greater than 10,000, the function returns -1 as an
error value.
 The statement on line 25 is never reached, because
whether or not the value is greater than 10,000, the
function returns before it gets to line 25, on either line 22
or line 24.
 A good compiler will warn that this statement cannot be
executed, and a good programmer will take it out! 82
Default Value in Parameters
 For every parameter you declare in a function prototype
and definition, the calling function must pass in a value.
 The value passed in must be of the declared type. Thus, if
you have a function declared as
long myFunction(int);
the function must in fact take an integer variable. If the
function definition differs, or if you fail to pass in an
integer, you will get a compiler error.
 The one exception to this rule is if the function prototype
declares a default value for the parameter.
 A default value is a value to use if none is supplied. The
preceding declaration could be rewritten as
long myFunction (int x = 50);
 This prototype says, "myFunction() returns a long and
takes an integer parameter. 83
 If an argument is not supplied, use the default value of
50." Because parameter names are not required in
function prototypes, this declaration could have been
written as
long myFunction (int = 50);
 The function definition is not changed by declaring a
default parameter.
 The function definition header for this function would be
long myFunction (int x)
 If the calling function did not include a parameter, the
compiler would fill x with the default value of 50.
 The name of the default parameter in the prototype need
not be the same as the name in the function header; the
default value is assigned by position, not name.
 Any or all of the function's parameters can be assigned
default values. 84
 The one restriction is this:
 If any of the parameters does not have a default value, no
previous parameter may have a default value.
 If the function prototype looks like
long myFunction (int Param1, int Param2, int Param3);
you can assign a default value to Param2 only if you have
assigned a default value to Param3.
 You can assign a default value to Param1 only if you've
assigned default values to both Param2 and Param3.
 The following example demonstrates the use of default
values.
// Examples of default parameter values
#include <iostream.h>
int AreaCube(int length, int width = 25, int height = 1);
int main() { 85
int length = 100;
int width = 50;
int height = 2;
int area;
area = AreaCube(length, width, height);
cout <<"The first area equals: " << area << "\n";
area = AreaCube(length, width);
cout <<"The second time area equals: " << area << "\n";
area = AreaCube(length);
cout <<"The third time area equals: " << area << "\n";
return 0;
}
AreaCube(int length, int width, int height) {
return (length * width * height);
} 86
 In the above program the AreaCube() prototype specifies that
the AreaCube() function takes three integer parameters. The
last two have default values.
 This function computes the area of the cube whose
dimensions are passed in.
 If no width is passed in, a width of 25 is used and a height
of 1 is used.
 If the width but not the height is passed in, a height of 1 is
used. It is not possible to pass in the height without passing in
a width.
 On lines 5-7, the dimensions length, height, and width are
initialized, and they are passed to the AreaCube() function
on line 9.
 The values are computed, and the result is printed on line 10.
87
 Execution returns to line 11, where AreaCube() is called
again, but with no value for height.
 The default value is used, and again the dimensions are
computed and printed.
 Execution returns to line 13, and this time neither the
width nor the height is passed in.
 Execution branches for a third time to line 17. The default
values are used. The area is computed and then printed.

88
Inline Functions
• When you define a function, normally the compiler creates
just one set of instructions in memory.
• When you call the function, execution of the program
jumps to those instructions, and when the function returns,
execution jumps back to the next line in the calling
function.
• If you call the function 10 times, your program jumps to
the same set of instructions each time. This means there is
only one copy of the function, not 10.
• There is some performance overhead in jumping in and out
of functions.
• It turns out that some functions are very small, just a line or
two of code, and some efficiency can be gained if the
program can avoid making these jumps just to execute one
or two instructions. 89
 When programmers speak of efficiency, they usually
mean speed: the program runs faster if the function call
can be avoided.
 If a function is declared with the keyword inline, the
compiler does not create a real function:
 it copies the code from the inline function directly into
the calling function.
 No jump is made; it is just as if you had written the
statements of the function right into the calling function.
 Note that inline functions can bring a heavy cost. If the
function is called 10 times, the inline code is copied into
the calling functions each of those 10 times.
 The tiny improvement in speed you might achieve is more
than swamped by the increase in size of the executable
program. 90
 Even the speed increase might be illusory.
 First, today's optimizing compilers do a terrific job on
their own, and there is almost never a big gain from
declaring a function inline.
 More important, the increased size brings its own
performance cost.
Example
//Program to demonstrates inline functions
#include <iostream.h>
inline int Double(int);
int main()
{
int target;
cout << "Enter a number to work with: ";
cin >> target;
cout << "\n";
91
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
return 0;
}
int Double(int target)
{
return 2*target;
}
92
• On line 3, Double() is declared to be an inline function
taking an int parameter and returning an int.
• The declaration is just like any other prototype except that
the keyword inline is prepended just before the return
value.
• This compiles into code that is the same as if you had
written the following: target = 2 * target; everywhere you
entered
target = Double(target);
• By the time your program executes, the instructions are
already in place, compiled into the OBJ file.
• This saves a jump in the execution of the code, at the cost
of a larger program.
• NOTE: Inline is a hint to the compiler that you would like
the function to be inlined. The compiler is free to ignore
the hint and make a real function call. 93
Recursion
• A function can call itself. This is called recursion, and
recursion can be direct or indirect.
• It is direct when a function calls itself; it is indirect
recursion when a function calls another function that then
calls the first function.
• Some problems are most easily solved by recursion,
usually those in which you act on data and then act in the
same way on the result.
• Both types of recursion, direct and indirect, come in two
varieties: those that eventually end and produce an answer,
and those that never end and produce a runtime failure.
• Programmers think that the latter is quite funny (when it
happens to someone else).
94
• It is important to note that when a function calls itself, a
new copy of that function is run.
• The local variables in the second version are independent
of the local variables in the first, and they cannot affect one
another directly, any more than the local variables in
main() can affect the local variables in any function it calls.
• To illustrate solving a problem using recursion, consider
the Fibonacci series: 1,1,2,3,5,8,13,21,34...
• Each number, after the second, is the sum of the two
numbers before it.
• A Fibonacci problem might be to determine what the 12th
number in the series is.
• One way to solve this problem is to examine the series
carefully. The first two numbers are 1.
95
• Each subsequent number is the sum of the previous two
numbers. Thus, the seventh number is the sum of the sixth
and fifth numbers. More generally, the nth number is the
sum of n - 2 and n - 1, as long as n > 2
• Recursive functions need a stop condition. Something must
happen to cause the program to stop recursing, or it will
never end.
• In the Fibonacci series, n < 3 is a stop condition. The
algorithm to use is this:
1. Ask the user for a position in the series.
2.Call the fib() function with that position, passing in the value
the user entered.
3. The fib() function examines the argument (n).
 If n < 3 it returns 1; otherwise, fib() calls itself (recursively)
passing in n-2, calls itself again passing in n-1, and returns
the sum. 96
• If you call fib(1), it returns 1.
• If you call fib(2), it returns 1.
• If you call fib(3), it returns the sum of calling fib(2) and
fib(1).
• Because fib(2) returns 1 and fib(1) returns 1, fib(3) will
return 2.
• If you call fib(4), it returns the sum of calling fib(3) and
fib(2).
• We've established that fib(3) returns 2 (by calling fib(2)
and fib(1)) and that fib(2) returns 1, so fib(4) will sum
these numbers and return 3, which is the fourth number in
the series.
• Taking this one more step, if you call fib(5), it will return
the sum of fib(4) and fib(3). 97
• We've established that fib(4) returns 3 and fib(3) returns 2,
so the sum returned will be 5.
• This method is not the most efficient way to solve this
problem (in fib(20) the fib() function is called 13,529
times!), but it does work. Be careful:
• if you feed in too large a number, you'll run out of
memory.
• Every time fib() is called, memory is set aside. When it
returns, memory is freed. With recursion, memory
continues to be set aside before it is freed, and this system
can eat memory very quickly. Listing 5.10 implements the
fib() function.
• WARNING: When you run Listing 5.10, use a small
number (less than 15). Because this uses recursion, it can
consume a lot of memory. 98
Example
// Program to demonstrate Recusrsion
// Finds the nth Fibonacci number
// Uses this algorithm: Fib(n) = fib(n-1) + fib(n-2)5:
// Stop conditions: n = 2 || n = 1
#include <iostream.h>
int fib(int n);
int main() {
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci
number\n";
return 0;
} 99
int fib (int n) {
cout << "Processing fib(" << n << ")... ";
if (n < 3 ) {
cout << "Return 1!\n";
return (1);
}
else {
cout << "Call fib(" << n-2 << ") and fib(" << n-1 <<").\n";
return( fib(n-2) + fib(n-1));
}
}

100
• The program asks for a number to find on line 9 and
assigns that number to target. It then calls fib() with the
target.
• Execution branches to the fib() function, where, on line 18,
it prints its argument.
• The argument n is tested to see whether it equals 1 or 2 on
line 12; if so, fib() returns. Otherwise, it returns the sums
of the values returned by calling fib() on n-2 and n-1.
• In the example, n is 5 so fib(5) is called from main().
• Execution jumps to the fib() function, and n is tested for a
value less than 3 on line 19.
• The test fails, so fib(5) returns the sum of the values
returned by fib(3) and fib(4). That is, fib() is called on n-2
(5 - 2 = 3) and n-1 (5 - 1 = 4). fib(4) will return 3 and
fib(3) will return 2, so the final answer will be 5.
101
• Because fib(4) passes in an argument that is not less than
3, fib() will be called again, this time with 3 and 2. fib(3)
will in turn call fib(2) and fib(1).
• Finally, the calls to fib(2) and fib(1) will both return 1,
because these are the stop conditions.
• The output traces these calls and the return values.
Compile, link, and run this program, entering first 1,
then 2, then 3, building up to 6, and watch the output
carefully.
• Then, just for fun, try the number 20. If you don't run out
of memory, it makes quite a show!
• Recursion is not used often in C++ programming, but it
can be a powerful and elegant tool for certain needs.

102

You might also like