Google+

81. 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:



Download this project:

Click here to download this project containing 'Factorial' and 'Recursion' class files used in this post (You can download the project and import into Eclipse IDE on your machine)




Please comment below to feedback or ask questions.

'Access Control' concept will be explained in the next post.


3 comments:

raghavi said...

public int fact(int n)
{
int result ;
if(n==1) return 1;
result = fact(n-1)*n;
return result;


}
arun why we giving return 1 i removed 1 and gave directly return result = fact(n-1)*n;
but its not working pls explain me how return 1 works

Arun Motoori said...

@Raghavi - I am returning 1 when fact(1) is called by placing a condition if(n==1) return 1. When the called value is greater than 1, fact(n-1)*n statement will be executed to call the fact() method recursively.

Understand the program by the below example -

1. When I call fact(5), the value of 5 will be passed to public int fact(int n) method

2. As 5 is not equal to 1, the value 1 is not returned i.e. return 1 statement is not executed. Instead the following statement result = fact(n-1)*n; will be executed. i.e. fact(5-1)*5 -> fact(4)*5; Hence fact(4) will be recursively called from this statement

3. In this way -> result = 1*2*3*4*5;

Hope you understood :)

Anjali Patel said...

i have a small doubt that static methods can only access static variable and methode
but here Recursive method is ststic eventhough we calling fact methode (which is non static)from this recursive methode .How it can be possible?