Week 12 - Lecture 32 - Recursion
Week 12 - Lecture 32 - Recursion
Dr Taimur Ahmed
Department of IT & CS, PAF-IAST
Lecture# 32
Recursion
Introduction to Recursion
❑ A recursive function is one that calls itself.
void Message(void)
{
cout << "This is a recursive function.\n";
Message();
}
❑ The above function displays the string
"This is a recursive function.\n", and then calls itself
❑ The function contains an if/else statement that controls the repetition. For
example, if we call the function:
Message(5);
❑ With each recursive call, the parameter controlling the recursion should move
closer to the base case
❑ Eventually, the parameter reaches the base case and the chain of recursive calls
terminates
Value of times: 2
Program Output
Function gives 3
Sum = 9
❑ Indirect recursion
➢ function A calls function B, and function B calls function A. Or,
//Return 0 when n is 0
if ( n <= 0 )
return 0;
else //recursive call
return n + sum(n-1);
❑ Factorial of n is denoted by n!
❑ The factorial of 0 is = 1
0!=1
1!=1
2!=2x1
3!=3x2x1
4!=4x3x2x1
n ! = n x (n-1) x … x 2 x 1 if n > 0
Lecture# 32 - Recursive Functions | 19
Creating a Factorial Function – Iterative
0!=1
1!=1=1x0!
2!=2x1=2x1!
3!=3x2x1=3x2!
4!=4x3x2x1=4x3!
int fact = 1;
for (int j = 1; j <= n; j++)
{
fact = fact * j;
}
Lecture# 32 - Recursive Functions | 20
Creating a Factorial Function – Recursive
❑ Factorial of n can be expressed in terms of the factorial of n-1
Let’s define a function fact()
0!=1
1 ! = 1 = 1 x fact(0)
2 ! = 2 x 1 = 2 x fact(1)
3 ! = 3 x 2 x 1 = 3 x fact(2)
4 ! = 4 x 3 x 2 x 1 = 4 x fact(3)
n ! = n x (n-1) x (n-2) x … x 1 = n x fact(n-1)
int fact(int n)
{
if (n == 0) //Base case
return 1;
else
return n * fact(n-1);
}
❑ After the starting two numbers, each term is the sum of the two
preceding terms
❑ Recursive solution:
fib(n) = fib(n – 1) + fib(n – 2);
❑ Base cases: n == 0, n == 1
Lecture# 32 - Recursive Functions | 23
Solving Recursively Defined Problems
❑ Iterative Implementation
+ Executes more efficiently than recursion
➢ May not be as natural as recursion for some problems