2. Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
4. WHAT IS RECURSION
• In simple language Recursion is the repeated
occurrence of a particular event
• In programming Recursion is the repeated
occurrence of a procedure as a result of the
procedure calling itself.
• Recursive procedure is the name given to the
procedures calling themselves.
• The parameters passed each time into the
function must be different.
5. Content of a Recursive Method
• Base case(s).
– Values of the input variables for which we perform no
recursive calls are called base cases (there should be at
least one base case).
– Every possible chain of recursive calls must eventually
reach a base case.
• Recursive calls.
– Calls to the current method.
– Each recursive call should be defined so that it makes
progress towards a base case.
6. Types of Recursion
• Single and Multiple Recursion
– Recursion that only contains a single self-
reference is known as single recursion. Eg:
Factorial function
– Recursion that contains multiple self-references is
known as multiple recursion. Eg: Fibonacci
function
7. Types of Recursion
• Direct And Indirect Recursion
– IF a Function F calls itself. (i.e) F calls F. Then this
recursion is Direct Recursion.
static int Direct (int n)
{
if (n<=0) return 0;
else return n + Direct (n-1);
}
8. Types of Recursion
• Indirect Recursion
– IF a Function F calls G. and Function G calls F. Then
this recursion is Indirect Recursion.
static int InDirect (int n)
{
if (n<=0) return 0;
else return n + Buddy (n-1);
}
int Buddy (int n)
{
return InDirect (n);
}
9. Recursively Defined Sequences
•Example:
•The sequence {an} of powers of 2 is given non
recursively by
an = 2n for n = 0, 1, 2, … .
•The same sequence can also be defined
Recursively:
a0 = 1
an+1 = 2an for n = 0, 1, 2, …
10. RECURSIVELY DEFINED FUNCTIONS
• Here is the non-recursive definition of the factorial
function:
– n! = 1· 2· 3· ··· · (n-1)· n
• Here is the recursive definition of a factorial:
(here f(n) = n!)
• The Java code for the Factorial function:
// recursive procedure for computing factorial
public static int Factorial(int n) {
if (n == 0) return 1; // base case
else return n * Factorial(n- 1); // recursive case
}
elsenfn
n
nf
)1(
0if1
)(
11. RECURSIVE ALGORITHMS
• Example: Recursive Fibonacci Algorithm
procedure fib(n: nonnegative integer)
if n = 0 then fib(0) := 0
else if n = 1 then fib(1) := 1
else fib(n) := fib(n – 1) + fib(n – 2)
14. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com