Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Recursion

Syllabus
Concept of recursion, simple recursive methods (e.g. factorial,
GCD, binary search, conversion of representations of numbers
between different bases).
Many problems can be solved very elegantly by observing that the solution can
be composed of solutions to ‘smaller’ versions of the same problem with the
base version having a known simple solution. Recursion can be initially
motivated by using recursive equations to define certain methods. These
definitions are fairly obvious and are easy to understand. The definitions can be
directly converted to a program. Emphasize that any recursion must have a
base case. Otherwise, the computation can go into an infinite loop. The tower
of Hanoi is a very good example of how recursion gives a very simple and
elegant solution whereas non-recursive solutions are quite complex
Recursive functions
• Recursion is a process in which a function calls itself as a
subroutine. This allows the function to be repeated several
times, since it calls itself during its execution. Functions that
incorporate recursion are called recursive functions.
Properties of Recursive Function
• Base case
• Condition that leads to a recursive method returning without making another
recursive call.
• Stops the recursion
• Solution to this case is simple enough to solve directly
• Calls itself to solve smaller sub-problems
• May combine the results of the sub-problems.
Example
• Calculation of factorial
5! = 5 x 4!
= 5 x 4 x 3!
= 5 x 4 x 3 x 2!
= 5 x 4 x 3 x 2 x 1!
=5x4x3x2x1
int fact(int n)
{
if(n==1)
return 1;
else
return n * fact(n-1);
}
1. Power function:
https://www.youtube.com/watch?v=mFb1Fj4sVcU&t=30s
2. Sum of n numbers:
https://www.youtube.com/watch?v=ngCos392W4w
3. Tower of Hanoi: https://www.youtube.com/watch?v=mFb1Fj4sVcU
void test (int count)
{
if (count = = 0)
System.out.println(“ ”);
else
{
System.out.println(“Bye” + count);
test( --count );
System.out.println(“ ” + count);
}
}
if else
test(3) SOP(Bye 3), test(2), SOP(2)
test(2) SOP(Bye 2), test(1), SOP(1)
test(1) SOP(Bye 1), test(0), SOP(0)
test(0) True, test(0) completed SOP(“ “) SOP(0)
test(1) completed SOP(1)
test(2) completed SOP(2)
test(3) completed SOP(3)

You might also like