Lec 05-Recursion
Lec 05-Recursion
Recursion
A function is said to be recursively defined, if a function
containing either a Call statement to itself or a Call statement
to a second function that may eventually result in a Call
statement back to the original function.
1. There must be certain criteria, called base criteria for which the function
does not call itself.
2. Each time the function does call itself(directly or indirectly), the argument
of the function must be closer to a base value.
Recursion
Iterative solution
Recursive solution
int fac(int numb){
int fac(int numb){
int product=1;
if(numb<=1)
return 1; while(numb>1){
else product *= numb;
return numb*fac(numb-1); numb--;
} }
return product;
}
Recursion
int result = 1;
while(result >0){
...
result++;
}
Recursion
• Recursive definition:
• F(0) = 0;
• F(1) = 1;
• F(number) = F(number-1)+ F(number-2);
Example 3: Fibonacci numbers
//Calculate Fibonacci numbers using recursive function.
//A very inefficient way, but illustrates recursion well
int fib(int n)
{
int f[n+1];
f[0] = 0; f[1] = 1;
for (int i=2; i<= n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}
Example 3: Binary Search
return 0;
}
Binary Search w/o recursion
1
2
3
A B C
• From the moves necessary to transfer one, two, and three disks, we
can find a recursive pattern - a pattern that uses information from
one step to find the next step.
1 21 - 1 = 2 - 1 = 1
2 22 - 1 = 4 - 1 = 3 3
23 - 1 = 8 - 1 = 7
4 24 - 1 = 16 - 1 = 15
5 25 - 1 = 32 - 1 = 31
6 26 - 1 = 64 - 1 = 63
• So the formula for finding the number of steps it takes to
transfer n disks from post A to post C is:
2 n- 1
Binomial coefficient
• Example: