4.1 Recursion
4.1 Recursion
1
TOPIC 4
Content
2
What is Recursion?
Recursion Or Iteration?
4
Recursive Definition
{
0 n=0
Sum(n) =
Sum(n-1) + n n>0
Recursive Definition
▪A recursive method
contains: public static int sum(int n){
i) Base case if(n == 0)
return 0;
▪ Case in recursive
else
definition in which the
return sum(n – 1) + n;
solution is obtained}
directly.
▪ Stops the recursion.
ii) General case
▪ Breaks problem into smaller versions of itself.
▪ Case in recursive definition in which a smaller version of
itself is called.
▪ Must eventually be reduced to a base case.
6
Tracing A Recursive Method
Tracing Example
sum(5) = sum(4) + 5 = 10 + 5 = 15
sum(4) = sum(3) + 4 = 6 + 4 = 10
sum(3) = sum(2) + 3 = 3 + 3= 6
sum(2) = sum(1) + 2 = 1 + 2 = 3
sum(1) = sum(0) + 1 = 0 + 1 = 1
sum(0 = return 0 Exercise:
factorial(n) = factorial(n-1) * n
factorial(1) = 1
when n = 4.
8
Recursive Type
▪ Indirectly
recursive : a method that calls another method and
eventually results in the original method call.
public static int abc(int m){ public static int xyz(int n){
... ...
xyz(m – 2); abc(n – 1);
} }
Recursive Type
10
Designing Recursive Methods
12
3! = 3 * 2! = 6
2! = 2 * 1! = 2
1! = 1 * 0! = 1
0! = 1
13
Example: Factorial Computation
0! = 1
3. Identify base cases 1! = 1
14
15
Example: Fibonacci Computation
▪ Fibonacci sequence:
▪ 0,1, 1, 2, 3, 5, 8, 13, 21, 34, … …
▪ Note:
▪ The third Fibonacci number is the sum of the first two Fibonacci
numbers.
▪ The fourth Fibonacci number in a sequence is the sum of the
second and third Fibonacci numbers.
2. Determine limiting conditions
first Fibonacci number is 0 and second Fibonacci number is 1
16
else
return fibonacci(no - 1) + fibonacci(no - 2);
17
Fibonacci Recursive Method
18
19
Other Examples
public static int largest(int list[], int lowerIndex, int upperIndex){
int max;
if(lowerIndex == upperIndex)
return list[lowerIndex];
else {
max = largest(list, lowerIndex + 1,upperIndex);
if(list[lowerIndex] >= max)
return list[lowerIndex];
else
return max;
} Largest Number in
} Array
20
Conclusion
22