Recursion

Can you call your self😅

It’s wired

But the method of java can call its self

When a method  call its self is called recursion

recursion syntax

1.	returntype methodname(){  
2.	//code to be executed  
3.	methodname();//calling same method  
4.	}  

Lets understand it by example :

public class RecursionExample {  
static void show(){  
System.out.println("hello");  
show();  
}  
  
public static void main(String[] args) {  
show();  
}  
}  
hello
hello
...
java.lang.StackOverflowError

in this program show() method call itself every  time

another example:

class Factorial {

    static int factorial( int n ) {
        if (n != 0)  // termination condition
            return n * factorial(n-1); // recursive call
        else
            return 1;
    }

    public static void main(String[] args) {
        int number = 4, result;
        result = factorial(number);
        System.out.println(number + " factorial = " + result);
    }
}
4 factorial = 24

Why we use recursion

  • Recursion help to write simple code
  • for problems like the tower of Hanoi we use recursion
  • We can write such codes also iteratively with the help of a stack data structure.
  • For example, use recursion in the Iterative Tower of Hanoi.


SHARE THIS PAGE





Important Link