Recursion
Recursion
WHAT IS RECURSION?
Sometimes, the best way to solve a problem is by
solving a smaller version of the exact same problem first
Recursion is a technique that solves a problem by
solving a smaller problem of the same type
WHEN YOU TURN THIS INTO A
PROGRAM, YOU END UP WITH
intFUNCTIONS
f(int x) THAT CALL THEMSELVES
{ (RECURSIVE FUNCTIONS)
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
PROBLEMS DEFINED RECURSIVELY
There are many problems whose solution can be defined
recursively
Example: n factorial
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0
1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*n if n > 0
CODING THE FACTORIAL FUNCTION
Recursive implementation
int Factorial(int n)
{
if (n==0) // base case
return 1;
else
return n * Factorial(n-1);
}
CODING THE FACTORIAL FUNCTION
(CONT.)
Iterative implementation
int Factorial(int n)
{
int fact = 1;
return fact;
}
RECURSION VS. ITERATION
int b(int x)
{
int z,y;
……………… // other statements
z = a(x) + y;
return z;
}
WHAT HAPPENS WHEN A
FUNCTION IS CALLED? (CONT.)
An activation record is stored into a stack (run-
time stack)
1) The computer has to stop executing function b and
starts executing function a
2) Since it needs to come back to function b later, it
needs to store everything about function b that is
going to need (x, y, z, and the place to start executing
upon return)
3) Then, x from a is bounded to w from b
4) Control is transferred to function a
WHAT HAPPENS WHEN A
FUNCTION IS CALLED? (CONT.)
After function a is executed, the activation record is
popped out of the run-time stack
All the old values of the parameters and variables in
function b are restored and the return value of function a
replaces a(x) in the assignment statement
WHAT HAPPENS WHEN A RECURSIVE
FUNCTION IS CALLED?
Except the fact that the calling and called functions have
the same name, there is really no difference between
recursive and nonrecursive calls
int f(int x)
{
int y;
if(x==0)
return 1;
else {
y = 2 * f(x-1);
return y+1;
}
}
2*f(2)
2*f(1)
2*f(1)
=f(0)
=f(1)
=f(2)
=f(3)
DECIDING WHETHER TO USE A
RECURSIVE SOLUTION