Chapter 05 Recursion
Chapter 05 Recursion
Introduction
Recursion is a repetitive process in which an
algorithm or function calls itself repeatedly until
some specified condition has been satisfied.
A function call itself is called a recursive function.
The recursive function must include a stopping
condition (anchor condition) or else the function
would never terminate (indefinite loop).
Example of the use of recursive algorithms:
Factorial, Fibonacci sequence (number) and Tower
of Hanoi.
Iteration vs. Recursion
There are two approaches to writing repetitive
algorithm: iteration & recursion.
Recursive algorithm take more storage and time than
the iterative version.
This is because a recursive function must store and
retrieve the value of each recursive call.
Although many function can be computed easily
without using recursion, there are others that are
easier to compute with recursion than without it.
Example: Tower of Hanoi game problem.
When to used Recursion?
If the algorithm or data structure naturally suited to
recursion. Example Quick Sort.
0, 1, 1, 2, 3, 5, 8, 13, 21, ?, ?
Example of fibonacci
F(0) = 0
F(1) = 1
F(2) = 0 + 1 = 1
F(3) = 1 + 1 = 2
F(4) = 1 + 2 = 3
F(5) = 2 + 3 = 5
F(6) = 3 + 5 = 8
Fibonacci algorithm
1. Begin
2. If (num = 0 or num = 1)
Stopping Condition (for which the function does
not call/refer to itself)
1.1 Return num
3. Return (fib(num-1) + fib(num-2)
4. End
Programming
//Fibbonaci sequence using recursion int fib(int n)
#include <stdio.h> {
#include <conio.h> if (num==0||num==1)
return num;
void main()
{ return (fib(num-1)+fib(num-2));
int fib(int); }
int num;
printf("\nEnter num for fibonacci
sequence: ");
scanf("%d",&num);
printf("\nFibonacci %d = Output:
%d",n,fib(num)); Enter n for fibonacci sequence: 4
getch(); Fibonacci 4 = 3
}
Exercise
Lab sheet 1: Power function using
Recursion