Chapter - 1 - Programming II - Copy
Chapter - 1 - Programming II - Copy
Functions
1. What is a function?
A function provides a convenient way of packaging a computational recipe, so that it can
be used as often as required.
Therefore, a function is a block of code designed to tackle a specific problem.
1
o 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.
2
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
In order to examine this code, first of all remember something said at the beginning of this
tutorial: a C++ program always begins its execution by the main function. So we will begin
there.
We can see how the main function begins by declaring the variable z of type int. Right after that,
we see a call to a function called addition. Paying attention we will be able to see the similarity
between the structure of the call to the function and the declaration of the function itself some
code lines above:
The parameters and arguments 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 function addition.
At the point at which the function is called from within main, the control is lost by main and
passed to function addition. The value of both arguments passed in the call (5 and 3) are copied
to the local variables int a and int b within the function.
Function addition declares another local variable (int r), and by means of the expression r=a+b, it
assigns to r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3
respectively, the result is 8.
The following line of code:
return (r);
finalizes function addition, and returns the control back to the function that called it in the first
place (in this case, main). At this moment the program follows its regular course from the same
point at which it was interrupted by the call to addition. But additionally, because the return
statement in function addition specified a value: the content of variable r (return (r);), which at
that moment had a value of 8. This value becomes the value of evaluating the function call.
So being the value returned by a function the value given to the function call itself when it is
evaluated, the variable z will be set to the value returned by addition (5, 3), that is 8. To explain
3
it another way, you can imagine that the call to a function (addition (5,3)) is literally replaced by
the value it returns (8).
Another example
#include<iostream.h>
#include<conio.h>
void starLine(); //prototype of the function with a name starLine
int main()
{
starLine(); //Calling the function with a name starLine
cout<< “Data type Range” << endl;
starLine();
cout<< “char -128 to 127” <<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;
}
void starLine()
{
for(int j=0;j<45;j++) definition of the function with a
cout<< “*”; name starLine
cout<<endl;
}
Given the next program, which function is the calling function and which is the called
function?
#include<iostream.h>
#include<conio.h>
void nextMsg()
int main()
{
cout<< “Hello!\n”;
nextMsg();
return 0;
}
void nextMsg()
4
{
cout<< “GoodBye!\n”;
return;
}
Eg.
int year = 1994;//global variable
int max(int,int);//gloabal funcrion
int main(void)
{
//…
}
Global variables are visible (“known”) from their point of definition down to the end
of the program.
Each block in a program defines a local scope. Thus the body of a function represents a
local scope. The parameters of a function have the same scope as the function body.
Variables defined within a local scope are visible to that scope only. Hence, a variable
need only be unique within its own scope. Local scopes may be nested, in which case
the inner scope overrides the outer scopes. Eg:
int xyz;//xyz is global
void Foo(int xyz)//xyz is local to the body of Foo
{
if(xyz > 0)
{
Double xyz;//xyz is local to this block
…
}
5
}
Eg
int num1;
void fun1(int num1)
{
//…
}
The global num1 is inaccessible inside fun1(), because it is overridden by the local
num1 parameter.
This problem is overcome using the scope operator ‘::’ which takes a global entity as
argument.
int num1 = 2;
void fun1(int num1)
{
//…
num1=33;
cout<<num1; // the out put will be 33
cout<<::num1; //the out put will be 2 which is the global
if(::num1 != 0)//refers to global num1
//…
}
6
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 declared explicitly, they will be declared to 0 automatically.
Eg. void my_fun()
{
static int num;
static int count = 2;
count=count*5;
num=num+4;
}
7
return 0;
}
o 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
o Passing arguments in this way, where the function creates copies of the arguments
passed to it is called passing by value.
o 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.
#.......
#.......
void order(int &, int &);
8
int main()
{
int n1 = 99, n2=11;
int n3 = 22, n4=88;
order(n1,n2);
order(n3,n4);
cout<< “n1=”<<n1<<endl;
cout<< “n2=”<<n2<<endl;
cout<< “n3=”<<n3<<endl;
cout<< “n4=”<<n4<<endl;
return 0;
}
void order(int & num1,int & num2)
{
if(num1 > num2)
{
int temp=num1;
num1 = num2;
num2 = temp;
}
}
o In main() there are two pairs of numbers-the first pair is not ordered and the second
pair is ordered. The order() function is called once for each pair, and then all the
numbers are printed out. The output revels that the first pair has been swapped
while the second pair has not. Here it is:
N1 = 11
N2 = 99
N3 = 22
N4 = 88
o In the order() function the first variable is called num1 and the second is num2. If
num1 is greater than num2, the function stores num1 in temp, puts num2 in num1,
and finally puts temp back in num2.
o 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.
10
1.9. Default arguments and function overloading
C++ has two capabilities that regular C doesn’t have. Default arguments and function
overloading.
11
}
//the following function definition is invalid as z is
//a parameter without a default and written after y
//parameters with default should always be at the
//right side of function declaration
void Mult_Dispaly (int x, int y=70, int z)
{
cout<< (x*y*z);
}
//thus the following function definition will be correct
void Mult_Dispaly (int x, int z, int y=70)
{
cout<< (x*y*z);
}
• When temp() is called, both the default parameters are used by the function.
• When temp(6) is called, the first argument becomes 6 while the default value
is used for the second parameter.
• When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
• When temp(3.4) is passed, the function behaves in an undesired way because
the second argument cannot be passed without passing the first argument.
12
Therefore, 3.4 is passed as the first argument. Since the first argument has
been defined as int, the value that is actually passed is 3.
13
fans = abs(p);//calling abs with float arguments
…
}
int abs(int i)
{
if(i<0)
Return i*-1;
else
Return I;
}
float abs(flaot x)
{
if(x<0.0)
Return x*-1.0;
else
Return x;
}
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
Exercise: Write four display overloaded function, which displays a given number.
1.10. 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.
The second line clearly indicates that factorial is defined in terms of itself and hence
can be expressed as a recursive function.
int Factorial(unsigned int n )
{
return n = = 0 ? 1 : n * factrial(n-1);
}
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
14
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.
15
Worksheet
1. Write an int function cube () that returns the cube of its single int formal parameter.
2. Write a float function triangle() that computes the area of a triangle using its two
formal parameters h and w, where h is the height and w is the length of the bases
of the triangle.
3. Write a float function rectangle() that computes and returns the area of a rectangle
using its two float formal parameters h and w, where h is the height and w is the
width of the rectangle
4. The formula for a line is given as y = mx + b. Write a function Line() that expects three
float parameters, slop m, y-intercept b, and x-coordinate x. the function computes the y-
coordinate associated with the line specified by m and b at x-coordinate.
5. Write a function Intersect() with four float parameters m1,b1,m2,b2. The
parameters come conceptually in two pairs. The first pair contains the coefficients
describing one line; the second pair contains coefficients describing a second line.
The function returns 1 if the two lines intersect. Otherwise, it should return 0;
6. Write a program that accepts a positive integer from the user and displays the
factorial of the given number. You should use a recursive function called
factorial() to calculate the factorial of the number.
7. Write another program that accepts a number from the user and returns the
Fibonacci value of that number. You should use recursion in here.
8. Develop a program that uses the function factorial() of exercise 6 to compute an
approximation of e (Euler’s number). Base your approximation on the following
formula for e:
1 + 1/1! + 1/2! + 1/3! + …
9. Write a function called isPrime() that accepts a number and determine whether the
number is prime or not.
10. Write a function called isEven() that uses the remainder operator(%) to determine
whether an integer is even or not.
11. Modify our calculator problem of worksheet using four functions
sum(),product(),quotient() and difference().
12. Write full program that calculates sum of the first N positive integers 1,2,…,N using recursive
function.
n
13. Write full program that computes the exponentiation A where A is a real number and N is a
positive integer using recursive function.
16