SlideShare a Scribd company logo
1 of 33
Download to read offline
Reema Thareja
Reema Thareja
Programming in C
Programming in C
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
CHAPTER 4
CHAPTER 4
Functions
Functions
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Introduction
Introduction
•
• C enables its programmers to break up
C enables its programmers to break up a program into segments commonly known as
a program into segments commonly known as functions
functions, each of
, each of
which can be written more or less independently of the others.
which can be written more or less independently of the others.
•
• Every function in the program is
Every function in the program is supposed to perform a well
supposed to perform a well-defined task. Theref
-defined task. Therefore, the code
ore, the code of one
of one
function is completely insulated from that of other
function is completely insulated from that of other functions.
functions.
•
• Every function has a name which acts as
Every function has a name which acts as an interface to the outside world in terms of how information is
an interface to the outside world in terms of how information is
transferred to it and how results generated by the function are transmitted back from it.
transferred to it and how results generated by the function are transmitted back from it.
•
• In the fig, main() calls another function, func1()
In the fig, main() calls another function, func1() to perform a well-defined task.
to perform a well-defined task.
•
• main() is known as the calling function and func1() is
main() is known as the calling function and func1() is known as the called function.
known as the called function.
•
• When the compiler encounters a function call,
When the compiler encounters a function call, instead of executing the next statemen
instead of executing the next statement in the calling
t in the calling
function, control jumps to the statements that are a part of
function, control jumps to the statements that are a part of the called function.
the called function.
•
•
After the called function is
After the called function is execute
executed, the control is
d, the control is returned back to the calling
returned back to the calling function.
function.
main()
main()
{
{
…………..
…………..
…………..
…………..
func1();
func1();
…………
…………
………..
………..
return 0;
return 0;
}
}
func1()
func1()
{
{
Statement Block;
Statement Block;
}
}
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Introduction Contd.)
Introduction Contd.)
•
• It is not necessary that the main() can call only one function, it can call as many functions as it
It is not necessary that the main() can call only one function, it can call as many functions as it
wants and as many times as it
wants and as many times as it wants. For example, a function call placed within a for loop,
wants. For example, a function call placed within a for loop,
while loop, or do-while loop
while loop, or do-while loop may call the same function multiple times until the condition
may call the same function multiple times until the condition
holds true.
holds true.
•
• It is not that only
It is not that only the main() can call another
the main() can call another functions. Any function can call any other
functions. Any function can call any other
function. In the figure, one function calls another, and the other function in turn calls some
function. In the figure, one function calls another, and the other function in turn calls some
other function.
other function.
main()
main()
{
{
…………..
…………..
…………..
…………..
func1();
func1();
…………
…………
………..
………..
return 0;
return 0;
}
}
func1()
func1()
{
{
………..
………..
…………
…………
func2();
func2();
………..
………..
……….
……….
return;
return;
}
}
func2()
func2()
{
{
………..
………..
…………
…………
func3();
func3();
………..
………..
……….
……….
return;
return;
}
}
func3()
func3()
{
{
…
…
…
.
.
…
…
…
.
.
…
…
…
…
…
…
…
…
…
…
…
.
.
…
…
…
.
.
…
…
…
.
…
…
…
.
return;
return;
}
}
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Why Do We Ne
Why Do We Need F
ed Functions?
unctions?
•
• Dividing the program into separate well-defined functions facilitates each function to
Dividing the program into separate well-defined functions facilitates each function to be written and
be written and
tested separately. This simplifies the process of getting the total program to work.
tested separately. This simplifies the process of getting the total program to work.
•
• Underst
Understanding, coding, and
anding, coding, and testing multiple separat
testing multiple separate functions are far easier
e functions are far easier than doing the same
than doing the same for
for
one large function.
one large function.
•
• If a big program has to be developed without the use of
If a big program has to be developed without the use of any function (excep
any function (except main()), then
t main()), then there will be
there will be
countless lines in the main() function.
countless lines in the main() function.
•
• All the libraries in C
All the libraries in C contain a set of functions
contain a set of functions that the programmer
that the programmers are
s are free to use
free to use in their programs.
in their programs.
These functions have been prewritten and pre-tested, so the programmers use them
These functions have been prewritten and pre-tested, so the programmers use them without worrying
without worrying
about their code details. This speeds
about their code details. This speeds up program development.
up program development.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Terminology of Functions
Terminology of Functions
•
• A function,
A function, f,
f, that uses another function,
that uses another function, g
g, is known as the
, is known as the calling function
calling function and g is known as the
and g is known as the called
called
function
function.
.
•
• The inputs that the function takes are known as
The inputs that the function takes are known as arguments.
arguments.
•
•
When a called function returns some result back to the calling function, it is said to
When a called function returns some result back to the calling function, it is said to return
return that result.
that result.
•
• The calling function may or may not pass
The calling function may or may not pass paramet
parameters
ers to the called function. If
to the called function. If the called function
the called function
accepts arguments, the calling function will pass
accepts arguments, the calling function will pass parameter
parameters, else
s, else not.
not.
•
• main() is the
main() is the function that is called by the
function that is called by the operating syste
operating system and, therefore, it is supposed
m and, therefore, it is supposed to return the
to return the
result of its processing to
result of its processing to the operating system.
the operating system.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
• Function
Function declaratio
declaration
n is a declaration statement that identifies a function with its name, a
is a declaration statement that identifies a function with its name, a list of
list of
arguments that it accepts, and the
arguments that it accepts, and the type of data it returns.
type of data it returns.
•
• The general format for declaring a function that accepts
The general format for declaring a function that accepts some arguments and returns some
some arguments and returns some value as
value as
result can be given as:
result can be given as:
return_da
return_data_type
ta_type function_name(data
function_name(data_type
_type variable1,
variable1, data_type
data_type variable2,…);
variable2,…);
•
• No function can be declared within the body of another function.
No function can be declared within the body of another function.
Exa
Exampl
mple,
e, flo
float
at av
avg
g (in
(int
t a,
a, int
int b);
b); //
//Ille
Illegal
gal
F
Function De
unction Declaration
claration
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
•
Function definition consists of a function header
Function definition consists of a function header that identifies the function, followed by the body of
that identifies the function, followed by the body of the
the
function containing the executable code for that function.
function containing the executable code for that function.
•
• When a function is
When a function is defined, space is allocated for that function in the
defined, space is allocated for that function in the memory
memory.
.
•
• The syntax of a function definition can be
The syntax of a function definition can be given as:
given as:
return_data_type function_name(data_type variable1, data_type variable2,...)
return_data_type function_name(data_type variable1, data_type variable2,...)
{
{
………….
………….
statements
statements
………….
………….
return( variable);
return( variable);
}
}
•
• The number and the order of arguments in the function header must be same
The number and the order of arguments in the function header must be same as that given in function
as that given in function
declaration statement.
declaration statement.
F
Function Defin
unction Definition
ition
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
F
Function
unction Call
Call
•
• The function call
The function call statemen
statement invokes the function.
t invokes the function.
•
• When a function is
When a function is invok
invoked, the Compiler jumps
ed, the Compiler jumps to the called function to
to the called function to execute the statem
execute the statements that
ents that
are a part of that function.
are a part of that function.
•
• Once the called function i
Once the called function is executed, the program contr
s executed, the program control passes
ol passes back to the calling function.
back to the calling function.
•
• Function call statement has the
Function call statement has the following synta
following syntax:
x:
function_name
function_name(variable1, Variable2, …);
(variable1, Variable2, …);
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
F
Function
unction Call
Call contd.)
contd.)
Points to Remember while Calling the Function:
Points to Remember while Calling the Function:
•
• Function name and the number and type of arguments in the function call must be same
Function name and the number and type of arguments in the function call must be same as that given in
as that given in
the function declaration and function header of
the function declaration and function header of the function definition.
the function definition.
•
• Names (and not the types)
Names (and not the types) of variables in function declaration, function call, and header of function
of variables in function declaration, function call, and header of function
definition may vary.
definition may vary.
•
• Arguments may be passed in the form of expressions to the called function. In such a case, arguments
Arguments may be passed in the form of expressions to the called function. In such a case, arguments
are first evaluated and conver
are first evaluated and converted to the
ted to the type of formal parameter and then the
type of formal parameter and then the body of the
body of the function
function
gets executed.
gets executed.
•
•
If the return type of the function is not
If the return type of the function is not void, then the value returned by the called function may be
void, then the value returned by the called function may be
assigned to some variable as given below:
assigned to some variable as given below:
Variable_name = Function_name
Variable_name = Function_name(variable1, Variable2, …);
(variable1, Variable2, …);
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Program that uses
Program that uses F
Function
unction
#include<stdio.h>
#include<stdio.h>
in
int s
t sum
um(i
(in
nt a
t a, i
, in
nt b
t b)
);
; //
// FU
FUNC
NCTI
TION
ON DE
DEC
CLA
LARA
RATI
TION
ON
int main()
int main()
{
{
int num1, num2, total = 0;
int num1, num2, total = 0;
printf(“
printf(“
n Enter the first number : “);
n Enter the first number : “);
scanf(“%d”, &num1);
scanf(“%d”, &num1);
printf(“
printf(“
n Enter the second number : “);
n Enter the second number : “);
scanf(“%d”, &num2);
scanf(“%d”, &num2);
t
to
ot
ta
al
l =
= s
su
um
m(
(n
nu
um
m1
1,
, n
nu
um
m2
2)
);
; /
//
/ F
FU
UN
NC
CT
TI
IO
ON
N C
CA
AL
LL
L
printf(“
printf(“
n Total = %d”, total);
n Total = %d”, total);
return 0;
return 0;
}
}
// FUNCTION DEFNITION
// FUNCTION DEFNITION
i
in
nt
t s
su
um
m (
( i
in
nt
t a
a,
, i
in
nt
t b
b)
) /
//
/ F
FU
UN
NC
CT
TI
IO
ON
N H
HE
EA
AD
DE
ER
R
{
{ /
//
/ F
FU
UN
NC
CT
TI
IO
ON
N B
BO
OD
DY
Y
return (a + b);
return (a + b);
}
}
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Return Statement
Return Statement
•
•
The
The return
return statemen
statement is used
t is used to terminate the execution of a function and return control to the
to terminate the execution of a function and return control to the calling
calling
function. When the return statement is encountered
function. When the return statement is encountered, the
, the program execut
program execution resumes in
ion resumes in the calling
the calling
function at the point immediately following the function call.
function at the point immediately following the function call.
•
• Programming
Programming Tip:
Tip: It is an error to
It is an error to use a return statement in a function that has void as its return type.
use a return statement in a function that has void as its return type.
•
•
A
A return
return statemen
statement may or
t may or may not return a value to
may not return a value to the calling function. The syntax of return statement
the calling function. The syntax of return statement
can be given as
can be given as
return <
return <expression>
expression> ;
;
•
• The value of
The value of expression
expression, if present, is returned to the calling function. However, in case
, if present, is returned to the calling function. However, in case expression
expression is
is
omitted, the return value of the function i
omitted, the return value of the function is undefined.
s undefined.
•
• By default, the ret
By default, the return type of a
urn type of a function is
function is int.
int.
•
• For functions that have no
For functions that have no return
return statemen
statement, the
t, the control automatically ret
control automatically returns to
urns to the calling
the calling function
function
after the last statement of the called function is
after the last statement of the called function is execute
executed.
d.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Passing Parameters to the
Passing Parameters to the F
Function
unction
•
• There are two ways in which
There are two ways in which arguments or parameter
arguments or parameters can be
s can be passed to the called
passed to the called function.
function.

 Call
Call by
by value
value in which values of the variables are passed by the
in which values of the variables are passed by the calling function to the called function.
calling function to the called function.

 Call
Call by
by reference
reference in which address of the variables are passed by the
in which address of the variables are passed by the calling function to the called
calling function to the called
function.
function.
Passing parameters to function
Passing parameters to function
C
Ca
al
ll
l b
by
y v
va
al
lu
ue
e C
Ca
al
ll
l b
by
y r
re
ef
fe
er
re
en
nc
ce
e
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Call by Value
Call by Value
•
• In the Call by Value method, the called function creates new variables to store the value of the arguments pass
In the Call by Value method, the called function creates new variables to store the value of the arguments passed to it.
ed to it.
Therefor
Therefore, the called function uses a
e, the called function uses a copy of the actual arguments to perform its intended task.
copy of the actual arguments to perform its intended task.
•
• If the called function is suppos
If the called function is supposed to modify the value of the parameters passed to it,
ed to modify the value of the parameters passed to it, then the change will be reflected
then the change will be reflected
only in the called function.
only in the called function. In the calling function no
In the calling function no change will be made to the value o
change will be made to the value of the variables.
f the variables.
#include<stdio.h>
#include<stdio.h>
void add( int n);
void add( int n);
int main()
int main()
{
{
int num = 2;
int num = 2;
printf("n The value of num before calling the function = %d", num);
printf("n The value of num before calling the function = %d", num);
add(num);
add(num);
printf("n The value of num after calling the function = %
printf("n The value of num after calling the function = %d", num);
d", num);
return 0;
return 0;
}
}
void add(int n)
void add(int n)
{
{
n = n + 10;
n = n + 10;
printf("n The value of num in the called function
printf("n The value of num in the called function = %d", n);
= %d", n);
}
}
The output of this
The output of this program is:
program is:
The value of num before calling the function = 2
The value of num before calling the function = 2
The value of num in the called functio
The value of num in the called function = 12
n = 12
The value of num after calling the function =
The value of num after calling the function = 2
2
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Call by Reference
Call by Reference
•
• When the calling function passes arguments to the called function using call by value method, the only
When the calling function passes arguments to the called function using call by value method, the only
way to return the modified value of
way to return the modified value of the argument to the caller is
the argument to the caller is explicitly using the return statement. A
explicitly using the return statement. A
better option when a function can modify the value of the argument is to pass arguments using Call by
better option when a function can modify the value of the argument is to pass arguments using Call by
Reference technique.
Reference technique.
•
• In call by reference, we declare the
In call by reference, we declare the function parameter
function parameters as
s as refer
references rather than normal
ences rather than normal variables.
variables.
When this is done, any changes made by the
When this is done, any changes made by the function to the arguments it received are visible in the
function to the arguments it received are visible in the
calling function.
calling function.
•
• T
To indicate that an argument is passed using
o indicate that an argument is passed using call by reference, an asterisk symbol (*)
call by reference, an asterisk symbol (*) is placed after the
is placed after the
type in the
type in the paramete
parameter list. This
r list. This way
way, changes made to
, changes made to that parameter in the called function body will
that parameter in the called function body will
then be reflected in its value
then be reflected in its value in the calling function.
in the calling function.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Program Illustrating Ca
Program Illustrating Call by Reference Technique
ll by Reference Technique
#include<stdio.h>
#include<stdio.h>
void
void add(
add( int
int *n);
*n);
in
int
t ma
main
in()
()
{
{
in
int
t nu
num
m =
= 2;
2;
printf("n The v
printf("n The value of num
alue of num befor
before calling the function
e calling the function = %d", num);
= %d", num);
add(num);
add(num);
printf("n The v
printf("n The value of num
alue of num after calling t
after calling the function = %d", num);
he function = %d", num);
return 0;
return 0;
}
}
void
void add(
add( int
int *n)
*n)
{
{
n = n + 10;
n = n + 10;
printf("n The v
printf("n The value of num
alue of num in the called fun
in the called function = %d", n);
ction = %d", n);
}
}
The output of this program is:
The output of this program is:
The value of num
The value of num befor
before calling the function
e calling the function = 2
= 2
The value
The value of num
of num in the called
in the called function = 1
function = 12
2
The value of num
The value of num after calling
after calling the function = 12
the function = 12
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Scope of Variables
Scope of Variables
•
•
In C, all constants and variables have a
In C, all constants and variables have a defined scope.
defined scope.
•
• By scope we mean
By scope we mean the accessibility and visibility of
the accessibility and visibility of the variables at different points in the program.
the variables at different points in the program.
•
• A variable or a constant in C has four types of scope: block,
A variable or a constant in C has four types of scope: block, function, file, and progra
function, file, and program scope.
m scope.
Variable Scope
Variable Scope
B
Bl
lo
oc
ck
k s
sc
co
op
pe
e F
Fu
un
nc
ct
ti
io
on
n s
sc
co
op
pe
e F
Fi
il
le
e s
sc
co
op
pe
e P
Pr
ro
og
gr
ra
am
m s
sc
co
op
pe
e
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Block Scope
Block Scope
•
• A statement block is a group of statements enclosed within an o
A statement block is a group of statements enclosed within an opening and closing curly brackets ({ }).
pening and closing curly brackets ({ }).
•
• If a variable is declared within a statement block, then
If a variable is declared within a statement block, then as soon as the control exits that
as soon as the control exits that block, the variable will cease to
block, the variable will cease to
exist.
exist.
•
• Such a variable also known as a local variable i
Such a variable also known as a local variable is said to have a block scope.
s said to have a block scope.
void main()
void main()
{
{ int
int x
x =
= 10,
10, i=0;
i=0;
printf("n The value of x outside the
printf("n The value of x outside the while loop is %d", x);
while loop is %d", x);
while (i<2)
while (i<2)
{
{ int
int x
x =
= i;
i;
printf("n The value of x inside the while
printf("n The value of x inside the while loop is %d", x);
loop is %d", x);
i++;
i++;
}
}
printf("n The value of x outside the
printf("n The value of x outside the while loop is %d", x);
while loop is %d", x);
}
}
Output:
Output:
The value of x outside the while loop is 10
The value of x outside the while loop is 10
The value of x inside the while loop is 0
The value of x inside the while loop is 0
The value of x inside the while loop is 1
The value of x inside the while loop is 1
The value of x outside the while loop is 10
The value of x outside the while loop is 10
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
• Fu
Func
ncti
tion
on sc
scop
ope
e is
is ap
app
pli
lic
ca
ab
ble
le o
onl
nly
y w
wit
ith
h g
got
oto
o la
labe
bel
l n
nam
ames
es.
. T
Th
hat
at is
is th
the
e pr
prog
ogr
ram
amme
mer
r c
can
ann
not
ot h
ha
av
ve
e th
the
e sa
same
me
la
labe
bel
l na
name
me in
insi
side
de a
a fu
func
ncti
tion
on.
.
F
Function
unction Scope
Scope
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
• If you want that functions should be able to access some variables which are not
If you want that functions should be able to access some variables which are not passed to them as
passed to them as
arguments, then declare those variables outside any function block.
arguments, then declare those variables outside any function block.
•
• Such variables are commonly known as global variables. Hence, global variables are those variables that
Such variables are commonly known as global variables. Hence, global variables are those variables that
can be accessed
can be accessed from any point in the
from any point in the program.
program.
#include<stdio.h>
#include<stdio.h>
int x = 10;
int x = 10;
void print();
void print();
int main()
int main()
{
{ pr
prin
intf(
tf("
"n Th
n The v
e valu
alue of
e of x in
x in ma
main
in() =
() = %d
%d", x
", x);
);
int x = 2;
int x = 2;
printf("n The value of local variable x in main() = %d",
printf("n The value of local variable x in main() = %d", x);
x);
print();
print();
}
}
void print()
void print()
{
{ pr
prin
intf(
tf("
"n Th
n The v
e valu
alue of
e of x in
x in pr
prin
int(
t() = %
) = %d"
d", x)
, x);
;
}
}
Output:
Output:
The value of x in the main() = 10
The value of x in the main() = 10
The value of local variable x in main() = 2
The value of local variable x in main() = 2
The value of x in print() = 10
The value of x in print() = 10
Program Scope
Program Scope
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
File Scope
File Scope
•
• When a global variable is accessible until the end of
When a global variable is accessible until the end of the file, the variable is said to have file scope.
the file, the variable is said to have file scope.
•
• T
To allow a
o allow a variable to have file scope, declare that
variable to have file scope, declare that variable with the static keywor
variable with the static keyword before specifying its
d before specifying its
data type:
data type:
sta
static i
tic int
nt x = 10
x = 10;
;
•
• A global static variable can be used anywhere from the file in which it is declared but it
A global static variable can be used anywhere from the file in which it is declared but it is not accessible
is not accessible
by any other file.
by any other file.
•
• Such variables ar
Such variables are useful when a pr
e useful when a programmer writes his
ogrammer writes his or her own
or her own header files.
header files.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Storage Classes
Storage Classes
•
•
The storage class of a variable defines the
The storage class of a variable defines the scope (visibility) and lifetime of variables and/or functions
scope (visibility) and lifetime of variables and/or functions
declared within a C Program.
declared within a C Program.
•
• In addition to this, the storage class gives
In addition to this, the storage class gives the following informatio
the following information about the variable or
n about the variable or the function.
the function.

 It is used to
It is used to determine the part of memory
determine the part of memory where storage space will be allocated for that variable or
where storage space will be allocated for that variable or
function (whether the variable/function will be stored in a register or
function (whether the variable/function will be stored in a register or in RAM).
in RAM).

 It specifies how long
It specifies how long the storage allocation will continue to exist for that function or variable.
the storage allocation will continue to exist for that function or variable.

 It specifies the scope of the variable or function. That is, the part of the C program in which the variable
It specifies the scope of the variable or function. That is, the part of the C program in which the variable
name is visible or accessible.
name is visible or accessible.

 It specifies whether the
It specifies whether the variable or function has internal, external, or no l
variable or function has internal, external, or no linkage.
inkage.

 It specifies whether the
It specifies whether the variable will be automatically initialized to zer
variable will be automatically initialized to zero or
o or to any indeterminate value.
to any indeterminate value.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
FEATURE
FEATURE
STORAGE CLASS
STORAGE CLASS
A
Au
ut
to
o E
Ex
xt
te
er
rn
n R
Re
eg
gi
is
st
te
er
r S
St
ta
at
ti
ic
c
Accessibility
Accessibility
Ac
Acce
cess
ssib
ible
le wi
with
thin
in th
the
e
function or block in which
function or block in which
it is declared
it is declared
Ac
Acce
cessi
ssibl
ble
e wi
with
thin
in
al
all
l pr
prog
ogr
ram
am fi
file
les
s
th
that are a
at are a pa
part
rt of
of
the program
the program
Acc
Access
essib
ible
le wit
within
hin th
the
e
fu
func
ncti
tion
on or
or bl
bloc
ock
k in
in
which it is declared
which it is declared
L
Lo
oc
ca
al
l:
: A
Ac
cc
ce
es
ss
si
ib
bl
le
e
within the function or
within the function or
bl
bloc
ock
k in
in wh
whic
ich
h it
it is
is
declared
declared
Gl
Glo
ob
ba
al:
l: A
Acc
cce
ess
ssib
ibl
le
e
within the program in
within the program in
which it is declared
which it is declared
S
St
to
or
ra
ag
ge
e M
Ma
ai
in
n M
Me
em
mo
or
ry
y M
Ma
ai
in
n M
Me
em
mo
or
ry
y C
CP
PU
U R
Re
eg
gi
is
st
te
er
r M
Ma
ai
in
n M
Me
em
mo
or
ry
y
Existence
Existence
Exists when the function
Exists when the function
o
or
r bl
blo
ock
ck in
in wh
whic
ich
h it
it is
is
d
de
ec
cl
la
ar
re
ed
d i
is
s e
en
nt
te
er
re
ed
d.
.
Ceases to exist when the
Ceases to exist when the
con
control return
trol returns
s fro
from
m the
the
fu
funct
nctio
ion
n or
or th
the
e blo
block
ck in
in
which it was declared
which it was declared
Exi
Exists
sts th
throu
rough
ghou
out
t
th
the
e e
ex
xec
ecut
utio
ion
n of
of
the program
the program
E
Ex
xi
is
st
ts
s w
wh
he
en
n t
th
he
e
fu
func
ncti
tion
on or
or bl
bloc
ock
k in
in
which it is declared is
which it is declared is
e
en
nt
ter
ere
ed.
d. Ce
Cea
ase
ses
s t
to
o
exist when the control
exist when the control
r
re
et
tu
ur
rn
ns
s f
fr
ro
om
m t
th
he
e
function or the block in
function or the block in
which it was declared
which it was declared
Loc
Local:
al: Re
Reta
tains
ins va
valu
lue
e
b
be
et
tw
we
ee
en
n f
fun
unc
cti
tion
on
calls or block entries
calls or block entries
G
Gl
lo
ob
ba
al:
l: P
Pr
re
es
se
erv
rve
es
s
value
value in progr
in program
am files
files
D
De
ef
fa
au
ul
lt
t v
va
al
lu
ue
e G
Ga
ar
rb
ba
ag
ge
e Z
Ze
er
ro
o G
Ga
ar
rb
ba
ag
ge
e Z
Ze
er
ro
o
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Recursive Functions
Recursive Functions
•
• A recursive function is a function that calls itself to solve a smaller version of
A recursive function is a function that calls itself to solve a smaller version of its task until a final call is
its task until a final call is
made which does
made which does not require a call to
not require a call to itself
itself.
.
•
• Every recursive solution has two major cases, they are
Every recursive solution has two major cases, they are

 base
base case
case, in which the problem is simple enough to
, in which the problem is simple enough to be solved directly without making any further calls
be solved directly without making any further calls
to the same function
to the same function

 recursive
recursive case
case, in which first the problem at hand is divided into simpler sub-parts. Second the function
, in which first the problem at hand is divided into simpler sub-parts. Second the function
calls itself but with
calls itself but with sub-parts of the problem obtained in the
sub-parts of the problem obtained in the first step. Third, the result is obtained by
first step. Third, the result is obtained by
combining the solutions of simpler sub-parts.
combining the solutions of simpler sub-parts.
•
• Theref
Therefore, recursion is defining large and complex problems
ore, recursion is defining large and complex problems in terms of a
in terms of a smaller and more easily
smaller and more easily
solvable problem.
solvable problem.
•
• In recursive functions, complicated problem is defined in terms of
In recursive functions, complicated problem is defined in terms of simpler problems and the
simpler problems and the simplest
simplest
problem is
problem is given explicitly.
given explicitly.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Finding Factorial o
Finding Factorial of a Num
f a Number using Recursion
ber using Recursion
PROBLEM
PROBLEM
5!
5!
=
= 5
5 X
X 4
4!
!
=
= 5
5 X
X 4
4 X
X 3
3!
!
=
= 5
5 X
X 4
4 X
X 3
3 X
X 2
2!
!
=
= 5
5 X
X 4
4 X
X 3
3 X
X 2
2 X
X 1
1!
!
SOLUTION
SOLUTION
5 X
5 X 4 X
4 X 3 X
3 X 2 X
2 X 1
1!
!
=
= 5
5 X
X 4
4 X
X 3
3 X
X 2
2 X
X 1
1
=
= 5
5 X
X 4
4 X
X 3
3 X
X 2
2
=
= 5
5 X
X 4
4 X
X 6
6
=
= 5
5 X
X 2
24
4
=
= 1
12
20
0
Base case
Base case is when n=1, because when n = 1, the result is
is when n=1, because when n = 1, the result is known to be 1
known to be 1
Recursive case
Recursive case of the factorial function will call itself
of the factorial function will call itself but with a smaller value of n, t
but with a smaller value of n, this case can be given as
his case can be given as
factorial(n)
factorial(n) =
= n
n factorial
factorial (n-1)
(n-1)
#include<stdio.h>
#include<stdio.h>
int Fact(int)
int Fact(int)
{
{ i
if
f(
(n
n=
==
=1
1)
)
return 1;
return 1;
else
else
return (n * Fact(n-1));
return (n * Fact(n-1));
}
}
main()
main()
{
{ i
in
nt
t n
nu
um
m,
, f
fa
ac
ct
to
or
ri
ia
al
l;
;
scanf(“%d”, &num);
scanf(“%d”, &num);
factorial=Fact(num);
factorial=Fact(num);
printf(“
printf(“
n Factorial of %d = %d”, num, factorial);
n Factorial of %d = %d”, num, factorial);
return 0;
return 0; © Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
}
}
T
Types of
ypes of Recursion
Recursion
•
• Any recursive function can be characterized based on:
Any recursive function can be characterized based on:

 whether the function calls itself
whether the function calls itself directly or indirectly (direct or
directly or indirectly (direct or indirect recursion)
indirect recursion)

 whether any operation is pending at each
whether any operation is pending at each recursive call (tail-recursive or not)
recursive call (tail-recursive or not)


the structure of the calling pattern (linear or
the structure of the calling pattern (linear or tree-recur
tree-recursive)
sive)
Tree
Tree
Direct
Direct Indirect
Indirect
Recursion
Recursion
Linear
Linear Tail
Tail
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Direct Recursion
Direct Recursion
•
• A function is said to be
A function is said to be directly
directly recursive if it explicitly calls
recursive if it explicitly calls itself
itself.
.
•
• For example, consider the function given below.
For example, consider the function given below.
in
int
t Fu
Func
nc(
( in
int
t n)
n)
{
{
if(n==0)
if(n==0)
return n;
return n;
else
else
return (Func(n-1));
return (Func(n-1));
}
}
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
•
A function is said to be
A function is said to be indirectly
indirectly recursive if it contains a call to
recursive if it contains a call to another function which ultimately calls
another function which ultimately calls
it. Look at the
it. Look at the functions given below
functions given below.
.
•
• These two functions are indirectly recursive as they both call each other.
These two functions are indirectly recursive as they both call each other.
in
int
t Fu
Func
nc1(
1(in
int
t n)
n)
{
{
if(n==0)
if(n==0)
return n;
return n;
else
else
return Func2(n);
return Func2(n);
}
}
in
int
t Fu
Func
nc2(
2(in
int
t x)
x)
{
{
return Func1(x-1);
return Func1(x-1);
}
}
Indirect Recursion
Indirect Recursion
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
int Fact(n)
int Fact(n)
{
{
return Fact1(n, 1);
return Fact1(n, 1);
}
}
int Fact1(int n, int res)
int Fact1(int n, int res)
{
{
if (n==1)
if (n==1)
return res;
return res;
else
else
return Fact1(n-1, n*res);
return Fact1(n-1, n*res);
}
}
•
• A recursive function is said to be
A recursive function is said to be tail recursive
tail recursive if no operations are pending to be
if no operations are pending to be performed when the
performed when the
recursive function returns to its caller.
recursive function returns to its caller.
•
• That is, when the
That is, when the called function returns, the returned value is
called function returns, the returned value is immediately return
immediately returned from the
ed from the calling
calling
function.
function.
•
• T
Tail recursive functions are highly desirable because they are
ail recursive functions are highly desirable because they are much more efficient to use as
much more efficient to use as in their
in their
case, the amount of
case, the amount of informat
information that has to
ion that has to be stored on the
be stored on the system stack is independent of the
system stack is independent of the
number of recursive calls.
number of recursive calls.
Tail Recursion
Tail Recursion
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Linear and
Linear and T
Tree Recursion
ree Recursion
•
• Recursive functions can also be c
Recursive functions can also be characteriz
haracterized depending on whether recursion grows in
ed depending on whether recursion grows in a linear fashion
a linear fashion
or forms a tree structure.
or forms a tree structure.
•
• In simple words, a recursive function is said to be
In simple words, a recursive function is said to be linearly
linearly recursive when no
recursive when no pending operation involves
pending operation involves
another recursive call to the function. For
another recursive call to the function. For example, the factorial function is linearly recursive as the
example, the factorial function is linearly recursive as the
pending operation involves only multiplication to be performed and does not
pending operation involves only multiplication to be performed and does not involve another call to
involve another call to
Fact.
Fact.
•
•
On the contrary, a recursive function is said to be
On the contrary, a recursive function is said to be tree
tree recursive (or
recursive (or non-linearly
non-linearly recursive) if the pending
recursive) if the pending
operation mak
operation makes another recursive call to
es another recursive call to the function. For example, the Fibonacci
the function. For example, the Fibonacci function (Fib) in
function (Fib) in
which the pending operations recursively call the Fib
which the pending operations recursively call the Fib function.
function.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Pros and Cons of Recursion
Pros and Cons of Recursion
•
• Pros: Recursive solutions often tend to be
Pros: Recursive solutions often tend to be shorter and simpler than
shorter and simpler than non-recursive ones.
non-recursive ones.

 Code is clearer and easier to use.
Code is clearer and easier to use.

 Recursion repres
Recursion represents like the original formula to
ents like the original formula to solve a problem.
solve a problem.

 Follows a divide-and-conquer technique to solve problems.
Follows a divide-and-conquer technique to solve problems.

 In some (limited)
In some (limited) instances, recur
instances, recursion may be
sion may be more efficient.
more efficient.
•
• Cons: For some
Cons: For some programme
programmers and readers, recursion is
rs and readers, recursion is a difficult concept.
a difficult concept.

 Recursion is implemented using system stack. If the stack space on
Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a
the system is limited, recursion to a
deeper level will be
deeper level will be difficult to implement.
difficult to implement.

 Aborting a recursive process in midstream is slow.
Aborting a recursive process in midstream is slow.

 Using a recursive function takes more memory
Using a recursive function takes more memory and time to execute as compared to
and time to execute as compared to its non-recursive
its non-recursive
counterpart.
counterpart.

 It is difficult to find bugs, particularly when using global variables.
It is difficult to find bugs, particularly when using global variables.
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Tower of Hanoi
Tower of Hanoi
•
• T
Tower of Hanoi is
ower of Hanoi is one of the
one of the main applications of a recursion. It
main applications of a recursion. It says, "if you can solve
says, "if you can solve n-1
n-1 cases, then
cases, then
you can easily solve the
you can easily solve the nth
nth case?"
case?"
A
A B
B C
C A
A B
B C
C
If there is only one ring,
If there is only one ring, then simply move the ring from source to the
then simply move the ring from source to the destination
destination
A
A B
B C
C A
A B
B C
C
A
A B
B C
C
A
A B
B C
C
If there are two rings, then first move ring 1 to the
If there are two rings, then first move ring 1 to the spare pole and then
spare pole and then
move ring 2 from source to the destination. Finally move ring 1 from the
move ring 2 from source to the destination. Finally move ring 1 from the
source to the destination
source to the destination
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
•
•
A
A B
B C
C
A
A B
B C
C
A
A B
B C
C
A
A B
B C
C
A
A B
B C
C A
A B
B C
C
A
A B
B C
C A
A B
B C
C
© Oxford University Press 2018. All rights reserved.
© Oxford University Press 2018. All rights reserved.
Consider the working with three rings.
Consider the working with three rings.

More Related Content

Similar to 662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf

Similar to 662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf (20)

user defined function
user defined functionuser defined function
user defined function
 
Functions
FunctionsFunctions
Functions
 
OOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptxOOP-Module-1-Section-4-LectureNo1-5.pptx
OOP-Module-1-Section-4-LectureNo1-5.pptx
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Function
FunctionFunction
Function
 
Functions
FunctionsFunctions
Functions
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Function
Function Function
Function
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 

Recently uploaded

Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 

Recently uploaded (20)

Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 

662213141-Tuxdoc-com-Programming-in-c-Reema-Thareja.pdf

  • 1. Reema Thareja Reema Thareja Programming in C Programming in C © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 2. CHAPTER 4 CHAPTER 4 Functions Functions © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 3. Introduction Introduction • • C enables its programmers to break up C enables its programmers to break up a program into segments commonly known as a program into segments commonly known as functions functions, each of , each of which can be written more or less independently of the others. which can be written more or less independently of the others. • • Every function in the program is Every function in the program is supposed to perform a well supposed to perform a well-defined task. Theref -defined task. Therefore, the code ore, the code of one of one function is completely insulated from that of other function is completely insulated from that of other functions. functions. • • Every function has a name which acts as Every function has a name which acts as an interface to the outside world in terms of how information is an interface to the outside world in terms of how information is transferred to it and how results generated by the function are transmitted back from it. transferred to it and how results generated by the function are transmitted back from it. • • In the fig, main() calls another function, func1() In the fig, main() calls another function, func1() to perform a well-defined task. to perform a well-defined task. • • main() is known as the calling function and func1() is main() is known as the calling function and func1() is known as the called function. known as the called function. • • When the compiler encounters a function call, When the compiler encounters a function call, instead of executing the next statemen instead of executing the next statement in the calling t in the calling function, control jumps to the statements that are a part of function, control jumps to the statements that are a part of the called function. the called function. • • After the called function is After the called function is execute executed, the control is d, the control is returned back to the calling returned back to the calling function. function. main() main() { { ………….. ………….. ………….. ………….. func1(); func1(); ………… ………… ……….. ……….. return 0; return 0; } } func1() func1() { { Statement Block; Statement Block; } } © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 4. Introduction Contd.) Introduction Contd.) • • It is not necessary that the main() can call only one function, it can call as many functions as it It is not necessary that the main() can call only one function, it can call as many functions as it wants and as many times as it wants and as many times as it wants. For example, a function call placed within a for loop, wants. For example, a function call placed within a for loop, while loop, or do-while loop while loop, or do-while loop may call the same function multiple times until the condition may call the same function multiple times until the condition holds true. holds true. • • It is not that only It is not that only the main() can call another the main() can call another functions. Any function can call any other functions. Any function can call any other function. In the figure, one function calls another, and the other function in turn calls some function. In the figure, one function calls another, and the other function in turn calls some other function. other function. main() main() { { ………….. ………….. ………….. ………….. func1(); func1(); ………… ………… ……….. ……….. return 0; return 0; } } func1() func1() { { ……….. ……….. ………… ………… func2(); func2(); ……….. ……….. ………. ………. return; return; } } func2() func2() { { ……….. ……….. ………… ………… func3(); func3(); ……….. ……….. ………. ………. return; return; } } func3() func3() { { … … … . . … … … . . … … … … … … … … … … … . . … … … . . … … … . … … … . return; return; } } © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 5. Why Do We Ne Why Do We Need F ed Functions? unctions? • • Dividing the program into separate well-defined functions facilitates each function to Dividing the program into separate well-defined functions facilitates each function to be written and be written and tested separately. This simplifies the process of getting the total program to work. tested separately. This simplifies the process of getting the total program to work. • • Underst Understanding, coding, and anding, coding, and testing multiple separat testing multiple separate functions are far easier e functions are far easier than doing the same than doing the same for for one large function. one large function. • • If a big program has to be developed without the use of If a big program has to be developed without the use of any function (excep any function (except main()), then t main()), then there will be there will be countless lines in the main() function. countless lines in the main() function. • • All the libraries in C All the libraries in C contain a set of functions contain a set of functions that the programmer that the programmers are s are free to use free to use in their programs. in their programs. These functions have been prewritten and pre-tested, so the programmers use them These functions have been prewritten and pre-tested, so the programmers use them without worrying without worrying about their code details. This speeds about their code details. This speeds up program development. up program development. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 6. Terminology of Functions Terminology of Functions • • A function, A function, f, f, that uses another function, that uses another function, g g, is known as the , is known as the calling function calling function and g is known as the and g is known as the called called function function. . • • The inputs that the function takes are known as The inputs that the function takes are known as arguments. arguments. • • When a called function returns some result back to the calling function, it is said to When a called function returns some result back to the calling function, it is said to return return that result. that result. • • The calling function may or may not pass The calling function may or may not pass paramet parameters ers to the called function. If to the called function. If the called function the called function accepts arguments, the calling function will pass accepts arguments, the calling function will pass parameter parameters, else s, else not. not. • • main() is the main() is the function that is called by the function that is called by the operating syste operating system and, therefore, it is supposed m and, therefore, it is supposed to return the to return the result of its processing to result of its processing to the operating system. the operating system. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 7. • • Function Function declaratio declaration n is a declaration statement that identifies a function with its name, a is a declaration statement that identifies a function with its name, a list of list of arguments that it accepts, and the arguments that it accepts, and the type of data it returns. type of data it returns. • • The general format for declaring a function that accepts The general format for declaring a function that accepts some arguments and returns some some arguments and returns some value as value as result can be given as: result can be given as: return_da return_data_type ta_type function_name(data function_name(data_type _type variable1, variable1, data_type data_type variable2,…); variable2,…); • • No function can be declared within the body of another function. No function can be declared within the body of another function. Exa Exampl mple, e, flo float at av avg g (in (int t a, a, int int b); b); // //Ille Illegal gal F Function De unction Declaration claration © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 8. • • Function definition consists of a function header Function definition consists of a function header that identifies the function, followed by the body of that identifies the function, followed by the body of the the function containing the executable code for that function. function containing the executable code for that function. • • When a function is When a function is defined, space is allocated for that function in the defined, space is allocated for that function in the memory memory. . • • The syntax of a function definition can be The syntax of a function definition can be given as: given as: return_data_type function_name(data_type variable1, data_type variable2,...) return_data_type function_name(data_type variable1, data_type variable2,...) { { …………. …………. statements statements …………. …………. return( variable); return( variable); } } • • The number and the order of arguments in the function header must be same The number and the order of arguments in the function header must be same as that given in function as that given in function declaration statement. declaration statement. F Function Defin unction Definition ition © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 9. F Function unction Call Call • • The function call The function call statemen statement invokes the function. t invokes the function. • • When a function is When a function is invok invoked, the Compiler jumps ed, the Compiler jumps to the called function to to the called function to execute the statem execute the statements that ents that are a part of that function. are a part of that function. • • Once the called function i Once the called function is executed, the program contr s executed, the program control passes ol passes back to the calling function. back to the calling function. • • Function call statement has the Function call statement has the following synta following syntax: x: function_name function_name(variable1, Variable2, …); (variable1, Variable2, …); © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 10. F Function unction Call Call contd.) contd.) Points to Remember while Calling the Function: Points to Remember while Calling the Function: • • Function name and the number and type of arguments in the function call must be same Function name and the number and type of arguments in the function call must be same as that given in as that given in the function declaration and function header of the function declaration and function header of the function definition. the function definition. • • Names (and not the types) Names (and not the types) of variables in function declaration, function call, and header of function of variables in function declaration, function call, and header of function definition may vary. definition may vary. • • Arguments may be passed in the form of expressions to the called function. In such a case, arguments Arguments may be passed in the form of expressions to the called function. In such a case, arguments are first evaluated and conver are first evaluated and converted to the ted to the type of formal parameter and then the type of formal parameter and then the body of the body of the function function gets executed. gets executed. • • If the return type of the function is not If the return type of the function is not void, then the value returned by the called function may be void, then the value returned by the called function may be assigned to some variable as given below: assigned to some variable as given below: Variable_name = Function_name Variable_name = Function_name(variable1, Variable2, …); (variable1, Variable2, …); © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 11. Program that uses Program that uses F Function unction #include<stdio.h> #include<stdio.h> in int s t sum um(i (in nt a t a, i , in nt b t b) ); ; // // FU FUNC NCTI TION ON DE DEC CLA LARA RATI TION ON int main() int main() { { int num1, num2, total = 0; int num1, num2, total = 0; printf(“ printf(“ n Enter the first number : “); n Enter the first number : “); scanf(“%d”, &num1); scanf(“%d”, &num1); printf(“ printf(“ n Enter the second number : “); n Enter the second number : “); scanf(“%d”, &num2); scanf(“%d”, &num2); t to ot ta al l = = s su um m( (n nu um m1 1, , n nu um m2 2) ); ; / // / F FU UN NC CT TI IO ON N C CA AL LL L printf(“ printf(“ n Total = %d”, total); n Total = %d”, total); return 0; return 0; } } // FUNCTION DEFNITION // FUNCTION DEFNITION i in nt t s su um m ( ( i in nt t a a, , i in nt t b b) ) / // / F FU UN NC CT TI IO ON N H HE EA AD DE ER R { { / // / F FU UN NC CT TI IO ON N B BO OD DY Y return (a + b); return (a + b); } } © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 12. Return Statement Return Statement • • The The return return statemen statement is used t is used to terminate the execution of a function and return control to the to terminate the execution of a function and return control to the calling calling function. When the return statement is encountered function. When the return statement is encountered, the , the program execut program execution resumes in ion resumes in the calling the calling function at the point immediately following the function call. function at the point immediately following the function call. • • Programming Programming Tip: Tip: It is an error to It is an error to use a return statement in a function that has void as its return type. use a return statement in a function that has void as its return type. • • A A return return statemen statement may or t may or may not return a value to may not return a value to the calling function. The syntax of return statement the calling function. The syntax of return statement can be given as can be given as return < return <expression> expression> ; ; • • The value of The value of expression expression, if present, is returned to the calling function. However, in case , if present, is returned to the calling function. However, in case expression expression is is omitted, the return value of the function i omitted, the return value of the function is undefined. s undefined. • • By default, the ret By default, the return type of a urn type of a function is function is int. int. • • For functions that have no For functions that have no return return statemen statement, the t, the control automatically ret control automatically returns to urns to the calling the calling function function after the last statement of the called function is after the last statement of the called function is execute executed. d. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 13. Passing Parameters to the Passing Parameters to the F Function unction • • There are two ways in which There are two ways in which arguments or parameter arguments or parameters can be s can be passed to the called passed to the called function. function.   Call Call by by value value in which values of the variables are passed by the in which values of the variables are passed by the calling function to the called function. calling function to the called function.   Call Call by by reference reference in which address of the variables are passed by the in which address of the variables are passed by the calling function to the called calling function to the called function. function. Passing parameters to function Passing parameters to function C Ca al ll l b by y v va al lu ue e C Ca al ll l b by y r re ef fe er re en nc ce e © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 14. Call by Value Call by Value • • In the Call by Value method, the called function creates new variables to store the value of the arguments pass In the Call by Value method, the called function creates new variables to store the value of the arguments passed to it. ed to it. Therefor Therefore, the called function uses a e, the called function uses a copy of the actual arguments to perform its intended task. copy of the actual arguments to perform its intended task. • • If the called function is suppos If the called function is supposed to modify the value of the parameters passed to it, ed to modify the value of the parameters passed to it, then the change will be reflected then the change will be reflected only in the called function. only in the called function. In the calling function no In the calling function no change will be made to the value o change will be made to the value of the variables. f the variables. #include<stdio.h> #include<stdio.h> void add( int n); void add( int n); int main() int main() { { int num = 2; int num = 2; printf("n The value of num before calling the function = %d", num); printf("n The value of num before calling the function = %d", num); add(num); add(num); printf("n The value of num after calling the function = % printf("n The value of num after calling the function = %d", num); d", num); return 0; return 0; } } void add(int n) void add(int n) { { n = n + 10; n = n + 10; printf("n The value of num in the called function printf("n The value of num in the called function = %d", n); = %d", n); } } The output of this The output of this program is: program is: The value of num before calling the function = 2 The value of num before calling the function = 2 The value of num in the called functio The value of num in the called function = 12 n = 12 The value of num after calling the function = The value of num after calling the function = 2 2
  • 15. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved. Call by Reference Call by Reference • • When the calling function passes arguments to the called function using call by value method, the only When the calling function passes arguments to the called function using call by value method, the only way to return the modified value of way to return the modified value of the argument to the caller is the argument to the caller is explicitly using the return statement. A explicitly using the return statement. A better option when a function can modify the value of the argument is to pass arguments using Call by better option when a function can modify the value of the argument is to pass arguments using Call by Reference technique. Reference technique. • • In call by reference, we declare the In call by reference, we declare the function parameter function parameters as s as refer references rather than normal ences rather than normal variables. variables. When this is done, any changes made by the When this is done, any changes made by the function to the arguments it received are visible in the function to the arguments it received are visible in the calling function. calling function. • • T To indicate that an argument is passed using o indicate that an argument is passed using call by reference, an asterisk symbol (*) call by reference, an asterisk symbol (*) is placed after the is placed after the type in the type in the paramete parameter list. This r list. This way way, changes made to , changes made to that parameter in the called function body will that parameter in the called function body will then be reflected in its value then be reflected in its value in the calling function. in the calling function. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 16. Program Illustrating Ca Program Illustrating Call by Reference Technique ll by Reference Technique #include<stdio.h> #include<stdio.h> void void add( add( int int *n); *n); in int t ma main in() () { { in int t nu num m = = 2; 2; printf("n The v printf("n The value of num alue of num befor before calling the function e calling the function = %d", num); = %d", num); add(num); add(num); printf("n The v printf("n The value of num alue of num after calling t after calling the function = %d", num); he function = %d", num); return 0; return 0; } } void void add( add( int int *n) *n) { { n = n + 10; n = n + 10; printf("n The v printf("n The value of num alue of num in the called fun in the called function = %d", n); ction = %d", n); } } The output of this program is: The output of this program is: The value of num The value of num befor before calling the function e calling the function = 2 = 2 The value The value of num of num in the called in the called function = 1 function = 12 2 The value of num The value of num after calling after calling the function = 12 the function = 12 © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 17. Scope of Variables Scope of Variables • • In C, all constants and variables have a In C, all constants and variables have a defined scope. defined scope. • • By scope we mean By scope we mean the accessibility and visibility of the accessibility and visibility of the variables at different points in the program. the variables at different points in the program. • • A variable or a constant in C has four types of scope: block, A variable or a constant in C has four types of scope: block, function, file, and progra function, file, and program scope. m scope. Variable Scope Variable Scope B Bl lo oc ck k s sc co op pe e F Fu un nc ct ti io on n s sc co op pe e F Fi il le e s sc co op pe e P Pr ro og gr ra am m s sc co op pe e © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 18. Block Scope Block Scope • • A statement block is a group of statements enclosed within an o A statement block is a group of statements enclosed within an opening and closing curly brackets ({ }). pening and closing curly brackets ({ }). • • If a variable is declared within a statement block, then If a variable is declared within a statement block, then as soon as the control exits that as soon as the control exits that block, the variable will cease to block, the variable will cease to exist. exist. • • Such a variable also known as a local variable i Such a variable also known as a local variable is said to have a block scope. s said to have a block scope. void main() void main() { { int int x x = = 10, 10, i=0; i=0; printf("n The value of x outside the printf("n The value of x outside the while loop is %d", x); while loop is %d", x); while (i<2) while (i<2) { { int int x x = = i; i; printf("n The value of x inside the while printf("n The value of x inside the while loop is %d", x); loop is %d", x); i++; i++; } } printf("n The value of x outside the printf("n The value of x outside the while loop is %d", x); while loop is %d", x); } } Output: Output: The value of x outside the while loop is 10 The value of x outside the while loop is 10 The value of x inside the while loop is 0 The value of x inside the while loop is 0 The value of x inside the while loop is 1 The value of x inside the while loop is 1 The value of x outside the while loop is 10 The value of x outside the while loop is 10 © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 19. • • Fu Func ncti tion on sc scop ope e is is ap app pli lic ca ab ble le o onl nly y w wit ith h g got oto o la labe bel l n nam ames es. . T Th hat at is is th the e pr prog ogr ram amme mer r c can ann not ot h ha av ve e th the e sa same me la labe bel l na name me in insi side de a a fu func ncti tion on. . F Function unction Scope Scope © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 20. • • If you want that functions should be able to access some variables which are not If you want that functions should be able to access some variables which are not passed to them as passed to them as arguments, then declare those variables outside any function block. arguments, then declare those variables outside any function block. • • Such variables are commonly known as global variables. Hence, global variables are those variables that Such variables are commonly known as global variables. Hence, global variables are those variables that can be accessed can be accessed from any point in the from any point in the program. program. #include<stdio.h> #include<stdio.h> int x = 10; int x = 10; void print(); void print(); int main() int main() { { pr prin intf( tf(" "n Th n The v e valu alue of e of x in x in ma main in() = () = %d %d", x ", x); ); int x = 2; int x = 2; printf("n The value of local variable x in main() = %d", printf("n The value of local variable x in main() = %d", x); x); print(); print(); } } void print() void print() { { pr prin intf( tf(" "n Th n The v e valu alue of e of x in x in pr prin int( t() = % ) = %d" d", x) , x); ; } } Output: Output: The value of x in the main() = 10 The value of x in the main() = 10 The value of local variable x in main() = 2 The value of local variable x in main() = 2 The value of x in print() = 10 The value of x in print() = 10 Program Scope Program Scope © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 21. File Scope File Scope • • When a global variable is accessible until the end of When a global variable is accessible until the end of the file, the variable is said to have file scope. the file, the variable is said to have file scope. • • T To allow a o allow a variable to have file scope, declare that variable to have file scope, declare that variable with the static keywor variable with the static keyword before specifying its d before specifying its data type: data type: sta static i tic int nt x = 10 x = 10; ; • • A global static variable can be used anywhere from the file in which it is declared but it A global static variable can be used anywhere from the file in which it is declared but it is not accessible is not accessible by any other file. by any other file. • • Such variables ar Such variables are useful when a pr e useful when a programmer writes his ogrammer writes his or her own or her own header files. header files. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 22. Storage Classes Storage Classes • • The storage class of a variable defines the The storage class of a variable defines the scope (visibility) and lifetime of variables and/or functions scope (visibility) and lifetime of variables and/or functions declared within a C Program. declared within a C Program. • • In addition to this, the storage class gives In addition to this, the storage class gives the following informatio the following information about the variable or n about the variable or the function. the function.   It is used to It is used to determine the part of memory determine the part of memory where storage space will be allocated for that variable or where storage space will be allocated for that variable or function (whether the variable/function will be stored in a register or function (whether the variable/function will be stored in a register or in RAM). in RAM).   It specifies how long It specifies how long the storage allocation will continue to exist for that function or variable. the storage allocation will continue to exist for that function or variable.   It specifies the scope of the variable or function. That is, the part of the C program in which the variable It specifies the scope of the variable or function. That is, the part of the C program in which the variable name is visible or accessible. name is visible or accessible.   It specifies whether the It specifies whether the variable or function has internal, external, or no l variable or function has internal, external, or no linkage. inkage.   It specifies whether the It specifies whether the variable will be automatically initialized to zer variable will be automatically initialized to zero or o or to any indeterminate value. to any indeterminate value. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 23. FEATURE FEATURE STORAGE CLASS STORAGE CLASS A Au ut to o E Ex xt te er rn n R Re eg gi is st te er r S St ta at ti ic c Accessibility Accessibility Ac Acce cess ssib ible le wi with thin in th the e function or block in which function or block in which it is declared it is declared Ac Acce cessi ssibl ble e wi with thin in al all l pr prog ogr ram am fi file les s th that are a at are a pa part rt of of the program the program Acc Access essib ible le wit within hin th the e fu func ncti tion on or or bl bloc ock k in in which it is declared which it is declared L Lo oc ca al l: : A Ac cc ce es ss si ib bl le e within the function or within the function or bl bloc ock k in in wh whic ich h it it is is declared declared Gl Glo ob ba al: l: A Acc cce ess ssib ibl le e within the program in within the program in which it is declared which it is declared S St to or ra ag ge e M Ma ai in n M Me em mo or ry y M Ma ai in n M Me em mo or ry y C CP PU U R Re eg gi is st te er r M Ma ai in n M Me em mo or ry y Existence Existence Exists when the function Exists when the function o or r bl blo ock ck in in wh whic ich h it it is is d de ec cl la ar re ed d i is s e en nt te er re ed d. . Ceases to exist when the Ceases to exist when the con control return trol returns s fro from m the the fu funct nctio ion n or or th the e blo block ck in in which it was declared which it was declared Exi Exists sts th throu rough ghou out t th the e e ex xec ecut utio ion n of of the program the program E Ex xi is st ts s w wh he en n t th he e fu func ncti tion on or or bl bloc ock k in in which it is declared is which it is declared is e en nt ter ere ed. d. Ce Cea ase ses s t to o exist when the control exist when the control r re et tu ur rn ns s f fr ro om m t th he e function or the block in function or the block in which it was declared which it was declared Loc Local: al: Re Reta tains ins va valu lue e b be et tw we ee en n f fun unc cti tion on calls or block entries calls or block entries G Gl lo ob ba al: l: P Pr re es se erv rve es s value value in progr in program am files files D De ef fa au ul lt t v va al lu ue e G Ga ar rb ba ag ge e Z Ze er ro o G Ga ar rb ba ag ge e Z Ze er ro o
  • 24. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved. Recursive Functions Recursive Functions • • A recursive function is a function that calls itself to solve a smaller version of A recursive function is a function that calls itself to solve a smaller version of its task until a final call is its task until a final call is made which does made which does not require a call to not require a call to itself itself. . • • Every recursive solution has two major cases, they are Every recursive solution has two major cases, they are   base base case case, in which the problem is simple enough to , in which the problem is simple enough to be solved directly without making any further calls be solved directly without making any further calls to the same function to the same function   recursive recursive case case, in which first the problem at hand is divided into simpler sub-parts. Second the function , in which first the problem at hand is divided into simpler sub-parts. Second the function calls itself but with calls itself but with sub-parts of the problem obtained in the sub-parts of the problem obtained in the first step. Third, the result is obtained by first step. Third, the result is obtained by combining the solutions of simpler sub-parts. combining the solutions of simpler sub-parts. • • Theref Therefore, recursion is defining large and complex problems ore, recursion is defining large and complex problems in terms of a in terms of a smaller and more easily smaller and more easily solvable problem. solvable problem. • • In recursive functions, complicated problem is defined in terms of In recursive functions, complicated problem is defined in terms of simpler problems and the simpler problems and the simplest simplest problem is problem is given explicitly. given explicitly. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 25. Finding Factorial o Finding Factorial of a Num f a Number using Recursion ber using Recursion PROBLEM PROBLEM 5! 5! = = 5 5 X X 4 4! ! = = 5 5 X X 4 4 X X 3 3! ! = = 5 5 X X 4 4 X X 3 3 X X 2 2! ! = = 5 5 X X 4 4 X X 3 3 X X 2 2 X X 1 1! ! SOLUTION SOLUTION 5 X 5 X 4 X 4 X 3 X 3 X 2 X 2 X 1 1! ! = = 5 5 X X 4 4 X X 3 3 X X 2 2 X X 1 1 = = 5 5 X X 4 4 X X 3 3 X X 2 2 = = 5 5 X X 4 4 X X 6 6 = = 5 5 X X 2 24 4 = = 1 12 20 0 Base case Base case is when n=1, because when n = 1, the result is is when n=1, because when n = 1, the result is known to be 1 known to be 1 Recursive case Recursive case of the factorial function will call itself of the factorial function will call itself but with a smaller value of n, t but with a smaller value of n, this case can be given as his case can be given as factorial(n) factorial(n) = = n n factorial factorial (n-1) (n-1) #include<stdio.h> #include<stdio.h> int Fact(int) int Fact(int) { { i if f( (n n= == =1 1) ) return 1; return 1; else else return (n * Fact(n-1)); return (n * Fact(n-1)); } } main() main() { { i in nt t n nu um m, , f fa ac ct to or ri ia al l; ; scanf(“%d”, &num); scanf(“%d”, &num); factorial=Fact(num); factorial=Fact(num); printf(“ printf(“ n Factorial of %d = %d”, num, factorial); n Factorial of %d = %d”, num, factorial); return 0; return 0; © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 26. } } T Types of ypes of Recursion Recursion • • Any recursive function can be characterized based on: Any recursive function can be characterized based on:   whether the function calls itself whether the function calls itself directly or indirectly (direct or directly or indirectly (direct or indirect recursion) indirect recursion)   whether any operation is pending at each whether any operation is pending at each recursive call (tail-recursive or not) recursive call (tail-recursive or not)   the structure of the calling pattern (linear or the structure of the calling pattern (linear or tree-recur tree-recursive) sive) Tree Tree Direct Direct Indirect Indirect Recursion Recursion Linear Linear Tail Tail © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 27. Direct Recursion Direct Recursion • • A function is said to be A function is said to be directly directly recursive if it explicitly calls recursive if it explicitly calls itself itself. . • • For example, consider the function given below. For example, consider the function given below. in int t Fu Func nc( ( in int t n) n) { { if(n==0) if(n==0) return n; return n; else else return (Func(n-1)); return (Func(n-1)); } } © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 28. • • A function is said to be A function is said to be indirectly indirectly recursive if it contains a call to recursive if it contains a call to another function which ultimately calls another function which ultimately calls it. Look at the it. Look at the functions given below functions given below. . • • These two functions are indirectly recursive as they both call each other. These two functions are indirectly recursive as they both call each other. in int t Fu Func nc1( 1(in int t n) n) { { if(n==0) if(n==0) return n; return n; else else return Func2(n); return Func2(n); } } in int t Fu Func nc2( 2(in int t x) x) { { return Func1(x-1); return Func1(x-1); } } Indirect Recursion Indirect Recursion © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 29. int Fact(n) int Fact(n) { { return Fact1(n, 1); return Fact1(n, 1); } } int Fact1(int n, int res) int Fact1(int n, int res) { { if (n==1) if (n==1) return res; return res; else else return Fact1(n-1, n*res); return Fact1(n-1, n*res); } } • • A recursive function is said to be A recursive function is said to be tail recursive tail recursive if no operations are pending to be if no operations are pending to be performed when the performed when the recursive function returns to its caller. recursive function returns to its caller. • • That is, when the That is, when the called function returns, the returned value is called function returns, the returned value is immediately return immediately returned from the ed from the calling calling function. function. • • T Tail recursive functions are highly desirable because they are ail recursive functions are highly desirable because they are much more efficient to use as much more efficient to use as in their in their case, the amount of case, the amount of informat information that has to ion that has to be stored on the be stored on the system stack is independent of the system stack is independent of the number of recursive calls. number of recursive calls. Tail Recursion Tail Recursion © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 30. Linear and Linear and T Tree Recursion ree Recursion • • Recursive functions can also be c Recursive functions can also be characteriz haracterized depending on whether recursion grows in ed depending on whether recursion grows in a linear fashion a linear fashion or forms a tree structure. or forms a tree structure. • • In simple words, a recursive function is said to be In simple words, a recursive function is said to be linearly linearly recursive when no recursive when no pending operation involves pending operation involves another recursive call to the function. For another recursive call to the function. For example, the factorial function is linearly recursive as the example, the factorial function is linearly recursive as the pending operation involves only multiplication to be performed and does not pending operation involves only multiplication to be performed and does not involve another call to involve another call to Fact. Fact. • • On the contrary, a recursive function is said to be On the contrary, a recursive function is said to be tree tree recursive (or recursive (or non-linearly non-linearly recursive) if the pending recursive) if the pending operation mak operation makes another recursive call to es another recursive call to the function. For example, the Fibonacci the function. For example, the Fibonacci function (Fib) in function (Fib) in which the pending operations recursively call the Fib which the pending operations recursively call the Fib function. function. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 31. Pros and Cons of Recursion Pros and Cons of Recursion • • Pros: Recursive solutions often tend to be Pros: Recursive solutions often tend to be shorter and simpler than shorter and simpler than non-recursive ones. non-recursive ones.   Code is clearer and easier to use. Code is clearer and easier to use.   Recursion repres Recursion represents like the original formula to ents like the original formula to solve a problem. solve a problem.   Follows a divide-and-conquer technique to solve problems. Follows a divide-and-conquer technique to solve problems.   In some (limited) In some (limited) instances, recur instances, recursion may be sion may be more efficient. more efficient. • • Cons: For some Cons: For some programme programmers and readers, recursion is rs and readers, recursion is a difficult concept. a difficult concept.   Recursion is implemented using system stack. If the stack space on Recursion is implemented using system stack. If the stack space on the system is limited, recursion to a the system is limited, recursion to a deeper level will be deeper level will be difficult to implement. difficult to implement.   Aborting a recursive process in midstream is slow. Aborting a recursive process in midstream is slow.   Using a recursive function takes more memory Using a recursive function takes more memory and time to execute as compared to and time to execute as compared to its non-recursive its non-recursive counterpart. counterpart.   It is difficult to find bugs, particularly when using global variables. It is difficult to find bugs, particularly when using global variables. © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 32. Tower of Hanoi Tower of Hanoi • • T Tower of Hanoi is ower of Hanoi is one of the one of the main applications of a recursion. It main applications of a recursion. It says, "if you can solve says, "if you can solve n-1 n-1 cases, then cases, then you can easily solve the you can easily solve the nth nth case?" case?" A A B B C C A A B B C C If there is only one ring, If there is only one ring, then simply move the ring from source to the then simply move the ring from source to the destination destination A A B B C C A A B B C C A A B B C C A A B B C C If there are two rings, then first move ring 1 to the If there are two rings, then first move ring 1 to the spare pole and then spare pole and then move ring 2 from source to the destination. Finally move ring 1 from the move ring 2 from source to the destination. Finally move ring 1 from the source to the destination source to the destination © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved.
  • 33. • • A A B B C C A A B B C C A A B B C C A A B B C C A A B B C C A A B B C C A A B B C C A A B B C C © Oxford University Press 2018. All rights reserved. © Oxford University Press 2018. All rights reserved. Consider the working with three rings. Consider the working with three rings.