04 Functions
04 Functions
Chapter 4
1
Functions
• A natural way to solve large problems is to break
them down into a series of sub-problems, which
can be solved independently and then combined
to arrive at a complete solution. In programming,
this methodology reflects itself in the use of sub-
programs, and in C++ all sub-programs are
called functions or methods.
• A function is a group of statements that together
perform a task. Every C++ program has at least
one function, which is main(), and all the most
trivial programs can define additional functions.
2
function declaration and definition
• A function declaration tells the compiler about a
function's name, return type, and parameters. A
function definition provides the actual body of
the function.
• The basic building block in a C program is
the function. Every C program is a collection of
one or more functions, written in some arbitrary
order. One and only one of these functions in the
program must have the name main(). This main
function is always the starting point of a C
program
3
The general form of a C++ function definition is
as follows:
return_type function_name( parameter list )
{
body of the function
}
The parentheses () which follow the name of the
function must be included even though they
apparently serve no purpose at this stage. The
function main() does not have to be at the top of
a program
4
Example 4.1: Write a program to print
the following figure
#####
#####
#####
#####
Hello
#####
#####
#####
#####
Byebye
#####
#####
#####
#####
5
Bad program
void main(void) // Bad program
{
int r , c ;
for(r = 1 ; r <= 4 ; r++) {
for(c = 1 ; c <= 5 ; c++) cout << " # " ;
cout << endl ;
}
cout << "Hello \n";
for(r = 1 ; r <= 4 ; r++) {
for(c = 1 ; c <= 5 ; c++) cout << " # " ;
cout << endl ;
}
cout << "Byebye \n";
for(r = 1 ; r <= 4 ; r++) {
for(c = 1 ; c <= 5 ; c++) cout << " # " ;
cout << endl ;
}
}
6
Good program: The main program
void print_hash(void) ;
void main(void)
{
print_hash();
cout << "Hello \n";
print_hash();
cout << "Byebye \n";
print_hash();
getch();
}
7
Good program: The function
void print_hash(void)
{
int r , c ;
for(r = 1 ; r <= 4 ; r++)
{
for(c = 1 ; c <= 5 ; c++) cout << " # " ;
cout << endl ;
}
return ;
}
8
• When a program begins running, the system
calls the main()function, that is, the system
starts executing codes from main() function.
When control of program reaches
to function_name() inside main(), the control
of program moves to void function_name(), all
codes inside void function_name() is executed
and control of program moves to code right
after function_name() inside main()
9
10
Function Declaration
In order to create and use a function, you must let
the compiler know about your function. A
function declaration tells the compiler about a
function name and how to call the function. The
actual body of the function can be defined
separately. In the previous example function is
declared using the sentence
void print_hash(void) ;
The syntax of declaring any function consists of
three parts as follows:
return_type function_name ( parameter list );
11
• The first part of declaring a function is the
return type.
• The second part in declaring a function is the
function name. A function name follows the
same rules we have applied to our variables
• The third part is the arguments (parameters)
list which the function expects to work.
12
Defining a function
• In order to use a function in your program, you
have to let the compiler know what the function
does. You define a function using the rule we
applied with the main() function. Define it
starting with its return value (if none, use void),
followed by the function name, its argument (if
any) between parentheses, and the body of the
function. Once you have defined a function, other
functions can use it. The body of the function
describes what the function is supposed to do.
13
Calling a Function Before Defining it
• If you define the function (write its name and
body) before use it. You do not have to declare
this function. But if you want to call a
function before defining it, you have to declare
the function before using it. This means that,
you must at least declare a function before
calling it.
14
Example 4.3
• Write an example to print the maximum
number among two integer numbers (100,200)
using a function.
• Write a main program to read 2 integer
numbers, then call a function to find and return
the bigger number, The main program will
print the bigger number.
15
int max(int, int );
int main ()
{
int a = 100, b = 200, ret;
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
16
int max(int num1, int num2)
{
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
17
Example 4.4: Write a program to
calculate a! + b! - c!
int madroob(int);
int main(void)
{
int a , b , c , res ;
cout << "Enter 3 numbers: ";
cin >> a >> b >> c ;
res = madroob(a) + madroob(b) - madroob(c);
cout << "Result = " << res << endl ;
getch();
return 0 ;
} 18
int madroob(int k)
{
int f , i ;
f=1;
for(i = k ; i >= 1 ; i--) f = f * i ;
return f;
}
19
Definition of Scope of Variable:
Scope of variable is defined as Region or Part of
Program in which the variable is visible / accessed /
valid .
Rules of Scope of Variable :
1. Local Variables are accessed / Visible only in
Local Block
2. Global variables can be explained from
anywhere in program
3. Priority is Given to Local variable if the two
variables are declared with same name but in
different blocks/functions
20
Local and Global Variables
• Local Variables are declared inside a function or
block. They can be used only by statements that
are inside that function or block of code. Local
variables are not known to functions outside their
own. It vanishes when the function returns.
• Global variables are defined outside of a
function, usually on top of the program. The
global variables will hold their value throughout
the lifetime of your program and they can be
accessed inside any of the functions defined for
the program.
21
Advantages and disadvantages
• Advantages of Local Variables :
Since data cannot be accessed from other functions , Data
Integrity is preserved. Only required data can be passed to
function , thus protecting the remaining data
• Disadvantages of Local Variables :
Common data required to pass again and again. They have
Limited scope
• Disadvantages of Global Variables :
Too many variables , if declared as global , then they
remain in the memory till program execution is over.
Unprotected data : Data can be modified by any function
22
Example 4.5:Write a program to print
this figure
#####
#####
#####
#####
Hello
####
####
####
Byebye
####
####
####
####
23
First solution using local variables
void shababik(int,int);
int main(void)
{
shababik(4,5);
cout << "Hello \n";
shababik(3,4);
cout << "Byebye \n";
shababik(4,4);
getch();
return 0;
}
24
void shababik(int h , int w)
{
int r , c ;
for(r = 1 ; r <= h ; r++)
{
for(c = 1 ; c <= w ; c++)
cout << " # " ;
cout << endl ;
}
return ;
}
25
Second solution using global variables
void shababik(void);
int h , w ;
int main(void)
{
h = 4 ; w = 5 ; shababik();
cout << "Hello \n";
h = 3 ; w = 4 ; shababik();
cout << "Byebye \n";
h = 4 ; w = 4 ; shababik();
getch();
return 0;
}
26
void shababik(void)
{
int r , c ;
for(r = 1 ; r <= h ; r++)
{
for(c = 1 ; c <= w ; c++)
cout << " # " ;
cout << endl ;
}
return ;
}
27
Example 4.6
Write a program to calculate
((1*2*3*....*a) + (1*2*3*......*b)) /
((1+2+3+...+c)*(1+2+3+.......+d))
28
int madroub(int n)
{
int fact , x ;
fact = 1 ;
for(x = 1 ; x <= n ; x++)
{ fact = fact * x ; }
return fact ;
}
29
int magmo3(int n)
{
int y , x ;
y=0;
for(x = 1 ; x <= n ; x++)
{ y=y+x; }
return y ;
}
30
void main(void)
{
int a , b , c , d ;
float final_result;
cout << "Enter values of a , b , c , d : ";
cin >> a >> b >> c >> d ;
final_result = float (madroub(a) + madroub(b)) /
(magmo3(c) * magmo3(d)) ;
cout << "Final result = " << final_result << endl;
}
31
Call by value and call by reference
• Call by Value: In this calling technique we pass
the values of arguments which are stored or
copied into the parameters of the function. Hence,
the original values are unchanged only the
parameters inside function changes.
• Call by Reference: In this we pass the address of
the variable as arguments. In this case the formal
parameter can be taken as a reference or a pointer,
in both the case they will change the values of the
original variable.
32
Example of calling by value
void calc(int x);
int main()
{ int x = 12; calc(x); cout << x; }
void calc(int x)
{ x = x + 10 ; }
Output : 12
33
• In this case the actual variable x is not
changed, because we pass argument by value,
hence a copy of x is passed, which is changed,
and that copied value is destroyed as the
function ends (goes out of scope). So the
variable x inside main() still has a value 12.
• But we can change this program to modify the
original x, by making the function calc() return
a value, and storing that value in x.
34
int calc(int x);
int main()
{ int x = 12; x = calc(x); cout << x ;}
Output : 22
35
Example of call by reference
void calc(int *p);
int main()
{ int x = 12; calc(&x); cout << x; }
Output : 22
36
Recursive function
• Recursion is the property that functions have to be
called by themselves. It is useful for some tasks,
such as sorting elements, or calculating the
factorial of numbers. For example, in order to
obtain the factorial of a number (n!) the
mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
More concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
37
// factorial calculator
#include <iostream>
using namespace std;
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}
38
Notice how in function factorial we included a call
to itself, but only if the argument passed was greater
than 1, since, otherwise, the function would perform
an infinite recursive loop, in which once it arrived to
0, it would continue multiplying by all the negative
numbers (probably provoking a stack overflow at
some point during runtime).
A recursive function must have 3 things
1. funcion call itself (another function with the same
name)
2. with each calling the problem must be smaller
3. It must have if condition (the smallest problem
which we can solve)
39