Recursion in C
Recursion in C
Recursion / Slide 2
Recursion
Recursion is the process of repeating items in a
self-similar way.
In programming languages, if a program allows
you to call a function inside the same function,
then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
Recursion / Slide 3
Recursion
In some problems, it may be natural to define
the problem in terms of the problem itself.
Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
Recursion / Slide 4
factorial function
The C equivalent of this definition:
int fac(int numb){
if(numb==1)
return 1;
else
return numb * fac(numb-1);
}
recursion means that a function calls itself
Recursion / Slide 6
factorial function
Assume the number typed is 3, that is, numb=3.
fac(3) :
3 == 1 ? No.
fac(3) = 3 * fac(2)
fac(2) :
2 == 1 ?
No.
fac(2) = 2 * fac(1)
fac(1) :
1 == 1 ? Yes.
return 1 int fac(int numb){
fac(2) = 2 * 1 = 2 if(numb==1)
return fac(2) return 1;
fac(3) = 3 * 2 = 6 else
return fac(3) return numb * fac(numb-1);
}
fac(3) has the value 6
Recursion / Slide 7
factorial function
For certain problems (such as the factorial function), a
recursive solution often leads to short and elegant code.
Compare the recursive solution with the iterative solution:
Recursion
Recursion
If we use iteration, we must be careful not to
create an infinite loop by accident:
Oops!
int result = 1;
while(result >0){
...
result++;
}
Oops!
Recursion / Slide 11
Recursion
Similarly, if we use recursion we must be
careful not to create an infinite chain of
function calls:
int fac(int numb){ Oops!
return numb * fac(numb-1); No termination
}
condition
Or:
int fac(int numb){
if (numb<=1)
return 1;
else
return numb * fac(numb+1);
}
Oops!
Recursion / Slide 12
Recursion
Recursion
Recursive definition:
F(0) = 0;
F(1) = 1;
F(number) = F(number-1)+ F(number-2);
Recursion / Slide 15
recursion
int fib(int n)
{
int f[100];
f[0] = 0; f[1] = 1;
for (int i=2; i<= n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}
Recursion / Slide 18
int recur_fn(parameters){
if(stopping condition)
return stopping value;
// other stopping conditions if needed
return function of recur_fn(revised parameters)
}
Recursion / Slide 19