Recursion

A recursion is the attribute that allows the method to call itself. A method that calls itself is said to be recursive method.

The classic example of recursion is the computation of factorial of a number.

Examples: 
  • Factorial of 3 is 3*2*1 = 6
  • Factorial of 6 is 6*5*4*3*2*1 = 720
Method calling itself for returning the factorial of a number:

int fact(int n)
{
     int result;

     if(n==1)
     return 1;
    
     result = fact(n-1)*n;
     return result;
}

Lets implement this factorial program on Eclipse IDE:

1. Create 'Factorial' class as shown below:


2. Create fact( ) method such that it receives integer value and returns the factorial of the received integer as show below and save:


3. Create another class named 'Recursion' as shown below:


 4. Create an object 'object1' to access fact( ) method in Factorial class as shown below:


5. Call the fact( ) method in Factorial class by passing an integer value for which we want to calculate the factorial as shown below:



6. Save and Run the 'Recursion' class as shown below:


7. Observe that output is displayed in console as shown below: