CHAPTER 2: Recursive
Functions
OUTLINES
❏ Definition of Recursion
❏ Example using Recursion
❏ Definition of Iteration
❏ Example using Iteration
❏ Recursion Vs Iteration
What is Recursion?
❏ Process in which a function calls itself repeatedly.
❏ Solves a particular problem by calling a copy of itself and
solving smaller sub problems of the original problems.
❏ Can reduce the length of the code.
❏ Make it easier to read and write.
Example
1. Write a recursive function to sum all nonnegative integers up to
n.
Factorial using Recursion
Factorial(n)
{
if(n <= 1) //Base case. 0! And 1! is always 1
{
return 1;
}
return n * Factorial(n-1); Task:
} Find the factorial of 5 using recursive
method.
Iteration
❏ It is defined as the repetition of computational or
mathematical procedure that continues until the
controlling condition becomes false.
Factorial using Iteration
FactorialusingLoop(n) Task:
{ Find the factorial of 5 using iterative
int factorial = 1; method.
for(int i = n; i > 0; i--)
{
factorial = factorial * i;
}
return factorial;
}
Recursion Vs Iteration
Task:
Write down five differences between recursion and iteration.
Exercises
1. Write a recursive function to find the Fibonacci series of n.
2. Find the output for the following program when x = 5 and y = 2.
function ( int x, int y )
{
if ( x == 0 )
return y
else
function( x-1, x+y )
}
THANK YOU