Class-Xii CH-11
Class-Xii CH-11
Class-Xii CH-11
By Vineet Saxena
RECURSION
Recursion is a programming technique in which a
function calls itself instead of calling other function.
Example
void A ( )
{
-------
-------
-------
A ( );
}
TYPES OF RECURSION
Direct Recursion
Indirect Recursion
Direct recursion
Linear Recursion
Binary Recursion
Tree Recursion
Nested Recursion
PARTS OF RECURSIVE FUNCTION
Base Case /Stopping case
Recursive Case/Inductive Case
Base Case
Recursive Case
Infinite Recursion
class xyz
{
{
if(i>5)
return 0;
else
{
int s = ob.cal(1);
System.out.print(“Total=“+s);
}}
Tail Recursion
Example
Display reverse even numbers from 20 to 2
// 20 18 16 14……..4 2
class xyz
{
{
if(i<2)
return ;
else
{
System.out.print(i+” “);
{
ob.test(20);
}}
Head recursion
Example
Display reverse even numbers from 20 to 2
// 20 18 16 14……..4 2
class xyz
{
public void test (int i)
{
if(i>20)
return ;
else
{
test(i +2); No tail/Head recursion
System.out.print(i+” “);
}
public static void main (String args[ ])
{
xyz ob = new xyz ();
ob.test(2);
}}
Binary recursion Example Binary Search
public int binary_search(int a[ ],int sn,int lb,int ub)
if(lb >ub) lb = lower bound
ub = upper bound
return -1; sn = number to be searched
int mi = (lb+ub)/2; a[] = array variable
if(sn.compareTo(a[mi])>0) mi = middle index
return binary_search(a,sn,mi+1,ub)
else if(sn.compareTo(a[mi])<0) Binary recursion
return binary_search(a,sn,lb,mi-1);
else
return mi;
}
Tree Recursion
Example : Fibonacci series
{
if(n<=1)
{
else
{
return fib(n-1)+fib(n-2);
}
}
Thank you…