Recursion in JAVA


AutomationChinnu

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:

View original post 78 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s