Chapter 5
Chapter 5
FUNCTIONS
What is function?
Function is group of program statements that can act on data and return a value.
It is a block of instructions that is executed when it is called from some other point of the program.
Every C++ program has at least one function, main ().
When your program starts, main () is called automatically. main ( ) might call other functions, some of which
might call still others.
• Where
– type is the type of data returned by the function
– name is the name by which it will be possible to call the function
– 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)
• The arguments act within the function like any other variables
• They allow passing parameters to the function when it is called
• The different parameters are separated by commas.
– statement is the function's body
• It can be a single instruction or
• a block of instructions in this case it must be delimited by a curly brackets{}
• As you can’t use variables before declarations (telling the compiler what the variable is),
you can’t use function before telling the compiler what this function is.
• The common approach to declare functions is at the beginning of the program.
The function declaration (function prototype) tells the compiler that later on in the program a function introduced
in the declaration is going to be used.
1
Example
void getnumber( ); this is a function declaration.
Void shows that the function doesn’t have a return type.
Function declaration is terminated with semicolon.
If the function has arguments, then they should be indicated in the declaration.
Function Definition
A function which returns nothing should have the return type void.
The body of a function contains the computational steps (statements) that contain the function.
Example
void getnumber ( ) function header
{
int x;
cout<< “Enter Number \n”; function body function body
cin>>number;
cout<<”The number you enterd is:”<<number;
}
The function body is placed in one place in memory. But it could be invoked in several places in the program.
Calling functions
Calling functions is invoking it to execute.
The function call involves the function name, followed by parentheses.
The function call is similar to its declaration except that the return type is not mentioned.
The call is terminated by semi colon.
Executing the call statement causes the function to execute, i.e. control is transferred to the function, the statements in the
function definition are executed and then control returns to the statement following the function call.
void add()
{
int a,b,c;
cout<<"enter two numbers \n";
cin>> a>>b; function body or function definition.
c = a + b;
cout <<" the sum is \t "<< c;
}
void sub ( )
{
int a,b,c;
cout<<"Enter two numbers \n";
cin>>a>>b; function body
cout<<"the difference is \t "<<a-b;
}
A Simple Function
The example below shows the definition of a simple function which raises an integer to the
power of another, positive integer.
• The function interface starts with the return type of the function (int in this case).
• The function name appears next followed by its parameter list.
Power has two parameters (base and exponent) which are of types int and unsigned int,
respectively
• Note that the syntax for parameters is similar to the syntax for defining variables: type identifier followed by the
parameter name.
• However, it is not possible to follow a type identifier with multiple comma-separated parameters:
The for-loop raises base to the power of exponent and stores the outcome in [Link], the function returns
result as the return value of the function.
Below, example 2 illustrates how this function is called. The effect of this call is that first the argument values 2 and 8 are,
respectively, assigned to the parameters base and exponent, and then the function body is evaluated.
Example 2:
3
When run, this program will produce the following output:
2 ^ 8 = 256
Example3:
scope of identifiers
Scope: - the scope of identifies is the part of the program in which it is known (for which the compiler
doesn’t say “undefined symbol”).
Structure of scopes
It’s not visible it’s something virtual (in c++)
Note:
• There can only be one program scope
• The program must exist before a fn is created
4
• Cannot put a function within a function (in c++) structure of functions is linear
• Cannot put block on top of the program it’s a allowed only within function.
• Blocks within blocks are allowed. Function and fn. prototype have names from the four scopes
Scope Rules
Rule 1: an identifier is known only within the scope in which it is declared;
and starting from its point of declaration down to the end of the scope.
Does this rule hold for labels whose scope is a function scope?
Rule 2: If an identifier is re-declared within a nested scope, it is the inner declaration that takes precedence
over the outer one.
Eg:
int fact (int n) int x=8; //outer x
{ int compute(int a, int b);
int i, p=f1; void main ( )
for (i=1, i<=n; i++) {
int x=4, y=3; //inner x
p = p * i;
x=y + compute (x, y);//3+(4*3)=12
return p; cout<<x; //and then the outer x
} } which is 8 so 12+3+8=23
void main ( )
{ int compute (int c, int d ) //output
int m,f; { // 23
cout<<”Enter a number:”; int m;
cin>>m;
f=fact (m); m=c*d; //3*4=12 8 x
cout<<”factorial”<<f; x=x+m;//8+12
return x; y 3
}
}
When a function calls itself, we call it recursion. A recursive function is a self-serving function.
When we are using identifiers we analyze the following:
Identifying the structure of the scope
Which identifier belongs to a given scope?
Determining the scope
Are we using the identifier within its scope?
M1 M2
Eg
int n, p;
void fact ( ) void main ( )
{ {
int i; cout << “enter a natural no”;
p=1; cin >> n; //main writes to n
for ( i = 1; j <= n; i ++)//fact reads n fact ( ); //main calls fact
p = p * i; //fact writes to p cout <<p; //main reads p
} }
________________________________________________________________________________________________
int n; for (i =1; i < = n; i ++)
int fact() p= p * i;
{ return p;
int I, p = 1; }
6
void main ( ) cin >> n;
{ f= fact ( );
int f; cout <<” factorial is ‘’ << f;
cout <<”Enter natural no:”; }
_______________________________________________________________________________________________
int n;
void fact ( )
{
int i, p =1; int i;
for (i= 1; i<= n; i ++) for(i-n-1; i>=; i--)
p= p * i; n = n*i;
n = p;
}
void main ( )
{
cout <<”Enter a natural no”;
cin >> n;
fact ( );
cout <<” factorial is” << n;
}
Note: Loading a variable with two information is obscure.
T1
Possibility Protection
P1 X
P2 X
P3
Note: T1Supports P3
int n;
void fact ( )
{
int i , p = 1;
for (i; =1; i<=n; i++)
p = p* i;
n=p;
}
void main ( )
{
int m;
cout << “enter a natural no’’;
cin >>n;
m=n;
fact ( );
cout <<”the factorial of “<<” is”<< n;
}
Common variables (Global variables)
Inhibits the independency & insulation of functions from each other.
Minizes security.
Frustrating for error tracking
Useful in creating variables & named constants that must be shared
B. Data Transfer through the return statement (T2 in c++)
7
The function identifier acts like a variable to transfer data from the called to the calling only
(if the return type is not a pointer or a reference).
It is a means of returning only one value to the calling function.
Simple types, pointers, struct & Unions are valid return types.
Failure to match the data type of the return value exactly with the function’s declared data type may not result in an error
when your program is compiled, but it may lead to undesired result, b/c the return value is always converted to the
appropriate type before being sent to the calling function.
eg
int n; // p1/ T1
int fact ( )
{ fact()
int i,j, p=1;
for (i = 1; i < = n; i++)
p=p*i;
return p; T1/P1 P2/T2
}
void main()
{ main()
inf f;
8
cout << “enter a natural no’’;
cin>>n;
f = fact ( );
cout < <” factorial of n:” < < ‘’ is” < < f;
}
Eg.
void fact(int n, int &p)
{
int i;
for(i=1; i<=n; i++)
p = p * i;
}
void main()
{
int n, p=1;
cout << “enter a natural no’’;
cin>>n;
fact(n, p);
cout<<”The factorial of “<<n<<” is”<<p;
}
#include <iostream.h>
void Foo (int& num);
int main (void)
{
int x = 10; output
Foo(x); x=0
cout << "x = " << x << '\n'; num=0
return 0; //the value in
} //name of num to x
void Foo (int& num)
0
{ num
num = 0;
cout << "num = " << num << '\n' ; x
10
}
10
Note:
Parameter passing by reference
- Allows the called function to have direct access (use & change) the values of the
variables defined in the calling function
- The address of the variable has to be passed to the called function.
- C++ provides two types of address parameters: references & pointers.
- Structures are always passed call-by-value: a copy of the entire structure is passed. But,
to get the performance of a call-by-reference and the protection of call-by-value, we can
use a pointer to a constant data (or a reference to a constant data).
- It is an appropriate parameter passing, when we need to return (to the calling function)
multiple values.
- To specify a reference to a constant, place the ‘const’ qualifier before the type specifier.
- Reference variables must be initialized in their declaration.
- Reference variables can’t be reassigned as aliases to other variables.
Example:
Write a modular program, that can accept a list of integers and displays the average of the
list of items. (Do not use global variables and return statements as a means of data transfer
mechanism)
U InputData
E main average
R
11
Function Overloading.
What is function overloading?
• Defining multiple functions with the same name is said to be function overloading.
• Two different functions can have the same name if the prototypes of their arguments are different.
• This means that you can give the same name to more than one function if they have either a
different number of arguments or different data types in their arguments.
Example:
void f(int i)
void (float f)
void f(int i,float f)
How C++ manages function overloading?
Name decoration (name managing) is a technique used to solve various problems caused by the
need to resolve unique names for programming entities in many modern programming languages like
C++,java…
Original function name decorated function name
void f(int i) ?f@@YAXH@Z(int i)
void f(float f) ?f@@YAXM@Z(float f)
void f(int i,float f) ?f@@YAXHM@Z(int i,float f)
YAXH,YAXM,YAXHM.
Example
# include<iostream.h>
int devide (int a, int b=2);
int devide(int z, int r, int y);
float devide (float a, float b);
int main()
{
int x=20, y=2;
float n=5.0, m=2.0;
cout<<devide(x,y);
cout<<endl;
cout<<devide(n,m);
cout<<endl;
cout<<devide(n,m,m);
cout<<endl;
return 0;
}
int devide (int a, int b)
{
return a/b;
}
int devide (int a, int b, int c)
{
int w=a/b
return w/c;
}
float devide (float x, float y)
{
return x/y;}
12
In this case we have defined two functions with the same name, but one of them accept two
arguments of type int and the other accepts them of type float the compiler knows which one to
call in each case by examining the type when the function is called.
If it is called with two ints as an argument it calls to the function that has two int arguments in
the prototype
if it is called with two floats it will call to the one which has two floats in its prototype.
For simplicity I have included the same code with both functions, but this is not compulsory.
You can make two functions with the same name but with completely different behavior.
Default arguments
What is Default argument in C++?
Function has argument when it is declared but called without it’s arguments.
In this case all the default arguments will substitute the missed arguments.
The default arguments should be indicated in the function declaration.
If one argument is missed when a function is called, then it is assumed to be the last argument,
it is impossible to leave arguments in the middle. //int add(int x,int y,int z) when it is called
add(a,b) y can’t be left .
In general the missed argument is assumed to be the last arguments. If there are two missed
arguments, then they are last two arguments. int add(int x,int y,int z,int k) when it is called
add(a,b) //the default arguments are the last two.
13
Inline Functions
What is an inline functions?
A type of function whose code gets inserted ,instead of jump to the function at the place where
there is a function call is known as an inline function.
Syntax:
inline type name ( )
int main()
{
int n= -3, m=4;
cout<<Abs(n);
cout<<Abs(m);
}
Recursion function
A function which calls itself is said to be recursive.
Take the factorial problem, for instance, which is defined as:
• Factorial of 0 is 1.
• Factorial of a positive number n is n times the factorial of n-1.
The second line clearly indicates that factorial is defined in terms of itself and hence can be expressed as a
recursive function:
14
return n == 0 ? 1 : n * Factorial(n-1);
}
For n set to 3, the table below provides a trace of the calls to Factorial.
The stack frames for these calls appear sequentially on the runtime stack, one after the other.
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.
The Factorial function, for example, has the termination condition n==0 which, when satisfied,
causes the recursive calls to fold back. (Note that for a negative n this condition will never be
satisfied and Factorial will fail).
As a general rule, all recursive functions can be rewritten using iteration. In situations where the
number of stack frames involved may be quite large, the iterative version is preferred. In other
cases, the elegance and simplicity of the recursive version may give it the [Link] factorial, for
example, a very large argument will lead to as many stack frames. An iterative version is
therefore preferred in this case:
# include<iostream.h>
int Factorial (unsigned int n);
int main()
{
int n;
cout<<"Enter a +ve number";
cin>>n;
cout<<"!"<<n<<"=:"<<Factorial(n);
return 0;
}
int Factorial (unsigned int n)
{
if (n = = 0)
return 1;
else
return (n*(factorial(n-1));
}
15
End of function.
Exercises
1. Write appropriate calls for the following functions to accomplish the specified task.
Tasks:
i) add 12.5 and 3
ii) display the result of 23.5 – 12 + 34,5
iii) display the result of 23 + 12.9 + 99 + 10.5
iv) display the sum of all numbers stored in an array
int key,input,nTrial=0,score;
void main()
{
clrscr();
randomize();
key=random(10)+1;
cout<<key<<endl;
do{
cout<<"\nMake your guess : ";
cin>>input;
nTrial++;
if(input==key)
{
cout<<"\nCorrect \n";
switch(nTrial)
{
case 1: score = 10; break;
case 2: score = 7; break;
case 3: score = 3; break;
}
16
}
else
cout<<"\nNot correct";
cout<<"\nSCORE = "<<score<<endl;
getch();
}
4. Define an enumeration called Month for the months of the year and use it to define a function which
takes a month as argument and returns it as a constant string.
5. Define an inline function called IsAlpha which returns nonzero when its argument is a letter, and
zero otherwise.
6. Write a function which draws a line of n asterisks, n being passed as a parameter to the function.
Write a driver program (a program that calls and tests the function) which uses the function to output
an mxn block of asterisks, m and n entered by the user.
17
7. Write a function which converts a sum of money given as an integer number of pence into a floating
point value representing the equivalent number of pounds. For example 365 pence would be 3.65
pounds.
10. # include<iostream.h>
void sum( int a, int b);
void main()
{
int x,y;
cin>>x>>y;
sum(x,y);
}
void sum ( int a, int b)
{
int sum=a+b;
cout<<"the sum="<<sum;
}
10.1 modify the function definition and the declaration of “sum()” in the above
problem if the main function is changed to
void main()
{
sum();
}
10.2 modify the main () function above if the in the above problem if the sum () is
modified as follow
float sum( float a, int b)
{
return (a+b);
}
18
// passing parameters by reference x=2, y=6, z=14
#include <iostream>
using namespace std;
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y <<
", z=" << z;
return 0;
}
19
else odd (a);
}
#include <iostream>
#include <string>
using namespace std;
string GetName()
{
string FirstName, LastName, FN;
return FN;
}
int main()
{
string FullName;
double Hours;
FullName = GetName();
Hours = GetHours(FullName);
return 0;
}
20
return TotalHours;
}
#include <iostream>
using namespace std;
while( b != 0 )
{
Remainder = a % b;
a = b;
b = Remainder;
}
return a;
}
int main()
{
int x, y;
return 0;
}
#include <iostream>
using namespace std;
21
int GCD(int a, int b)
{
while( 1 )
{
a = a % b;
if( a == 0 )
return b;
b = b % a;
if( b == 0 )
return a;
}
}
int main()
{
int x, y;
return 0;
}
22