Chapter-2 - Function
Chapter-2 - Function
Functions
1
● 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
3
Functions in C++
Objectives
Basic concept and need of function
Declaring and defining a function
Function components (parameters and
arguments)
Calling /invoking function by value and
reference parameters
Recursive function
4
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.
5
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 can contain up to 32 characters, they must begin with a
letter, and they can consist of letters, numbers, and the
underscore (_) character.
● 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.
6
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.
8
Defining a function (function 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. The definition consists of a line called
the decelerator.
● If function definition is done before the main
function, then there is no need to put the prototype,
otherwise the prototype should be scripted before
the main function starts.
9
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.
10
● 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
11
Lets have another very simple function example:
#include<iostream>
Using namespace std;
void starLine(); //function prototype
int main()
//func definition
{
void starLine()
starLine(); //Calling the function with a name {
starLine for(int
cout<< “Data type Range” << endl; j=0;j<45;j++)
starLine(); cout<< “*”;
cout<< “char -128 to 127” <<endl cout<<endl;
<< “short -32,768 to 32,767” <<endl }
<< “ int system dependent” <<endl
<< “long -2,147,483,648 to 2,147,483,647” <<
endl;
starLine();
return 0;
}
12
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;
}
13
Function Parameters and arguments
return 0;
}
15
● 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
16
Passing 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 above:
17
#.....
int main()
{
int x = 10;
Foo(x);
cout<< “x = ”<<x<< “\n”;
return 0;
}
x=0
Look at the next example
● 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.
19
#.......
void order(int &, int &);
int main()
{
int n1 = 99, n2=11; void order(int &num1,int &num2)
int n3 = 22, n4=88; {
order(n1,n2); if(num1 > num2)
{
order(n3,n4);
int temp=num1;
cout<< “n1=”<<n1<<endl; num1 = num2;
cout<< “n2=”<<n2<<endl; num2 = temp;
cout<< “n3=”<<n3<<endl; }
cout<< “n4=”<<n4<<endl; }
return 0;
}
20
● Using reference arguments in this way is a sort of
remote control operation. The calling program tells
the function what variables in the calling program to
operate on, and the function modifies these variables
without ever knowing their real names.
21
Global versus local variables
● Everything defined at the program scope level (outside
functions) is said to have a global scope.
○ Eg.
23
Scope Operator
● Because a local scope overrides the global scope,
having a local variable with the same name as a
global variable makes the latter inaccessible to the
local scope.
Eg
int num1;
void fun1(int num1)
{
//…
}
24
Solution???
● Use scope operator ‘::’ which takes a global entity as argument.
int num1 = 2;
//…
num1=33;
//…
25
Automatic versus static variables
● describe what happens to local variables
when a function returns to the calling
procedure.
● By default, all local variables are automatic.
○ meaning are erased when the function
ends. They use prefix auto
Eg. main()
{
int i;
auto float x;
…
}
26
● The opposite of an automatic is a static
variable.
● All global variables are static and
● all static variables retain their values.
● Therefore, if a local variable is static, it too
retains its value when its function ends -in
case this function is called a second time.
● static is a keyword to declare a static
variable.
27
● Static variables can be declared and
initialized within the function, but the
initialization will be executed only once
during the first call.
● If static variables are not initialized
explicitly, they will be declared to 0
automatically.
28
void my_fun(){
int num2=9;
static int num;
static int count = 2;
count=count*5;
num=num+4; num2+=2; void main () {
cout<<“Num:”<<num my_fun();
<<“ Count:”<<count my_fun();
<<“Num2”<<num2; my_fun();
<<endl; }
}
void main()
{ int a=40, b=50, c=60; Muti_Display(‘A’, 5);
Add_Display(a,b,c); //will print 150 (ie 40+50+60)
Add_Display(a,b); //will print 120 (ie 40+50+30)
Add_Display(a); //will print 90 (ie 40+20+30)
Add_Display(); //will print 60 (ie 10+20+30)
Mult_Display(a,b); //will print 2000 (40*50)
Mult_Display(a); //will print 2800 (40*70)
//Mult_Display() //is invalid as there is no default for x 35
//parameters with default should always be at the
//right side of function declaration
37
● Suppose that you write a function that return the absolute value of what ever number you
passed to it:
int iabs(int i)
{ if(i<0)
return (i*-1);
else
return (i);
}
float fabs(float x)
{ if(x<0.0)
return (x * -1.0);
else
return (x);
}
38
● 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:
39
int abs(int i)
int abs ( int i ); {
if(i<0)
return i*-1;
float abs ( float x ); else
return I;
}
int main ( )
{
float abs(flaot x)
… {
if(x<0.0)
return x*-1.0;
ians = abs(i);//calling abs else
return x;
with int arguments }
fans = abs(p);//calling
abs with float
arguments
40
• 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
41
Recursion
● A function which calls itself is said to be recursive.
● Recursion is a general programming technique applicable
to problems which can be defined interms of themselves.
● Take the factorial problem, for instance which is defined as:
○ factorial of 0 is 1
○ factorial of a positive number n is n time the factorial of n-1.
42
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
43
44
● The stack frames for these calls appear
sequentially on the runtime stack, one after the
other.
● Stack frame – The section of memory where the
local variables, arguments, return address and
other information of a function are stored, is called
stack frame or activation record.
● A recursive function must have at least one
termination condition which can be satisfied.
● Otherwise, the function will call itself indefinitely
until the runtime stack overflows.
45
● The three necessary components in a recursive method
are:
46
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.
47
● Try to use a recursive function call to solve
the Fibonacci series. The Fibonacci series is :
○ 0,1,1,2,3,5,8,13,21,…
● The recursive definition of the Fibonacci
series is as follows:
○ Fibonacci (0) =0
○ Fibonacci (1) =1
○ Fibonacci (n) =Fibonacci (n-1) +Fibonacci (n-2);
48
49
Recursion versus iteration
● Both iteration and recursion are based on control structure.
○ Iteration uses a repetition structure (such as for, while, do…while)
and
○ recursive uses a selection structure (if, if else or switch).
● Both iteration and recursive can execute infinitely-an infinite
loop occurs with iteration if the loop continuation test become
false and infinite recursion occurs if the recursion step doesn’t
reduce the problem in a manner that coverage on a base case.
● Recursion has disadvantage as well. It repeatedly invokes the
mechanism, and consequently the overhead of method calls.
This can be costly in both processor time and memory space.
Each recursive call creates another copy of the method
(actually, only the function’s variables); this consumes
considerable memory.
50
● N.B: Use recursion if:
○ A recursive solution is natural and easy to
understand
○ A recursive solution doesn’t result in
excessive duplicate computation.
○ the equivalent iterative solution is too
complex and
○ of course, when you are asked to use one in the
exam!!
51
Chapter End!
52