Recursion in Java

Java supports recursion.Recursion is the process of defining something in terms of itself. As it relates to Java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3 factorial is 1 * 2 * 3 or 6.

Here is how a factorial can be computed by use of a recursive method :

// A simple example of recursion.
class Factorial {
// this is a recursive method.
int fact ( int n) 
{
int result ;
if (n==1)
return 1;
result = fact (n-1) * n ; return result ;
}}
class Recursion  (
public static void main ( String args[] ) 
{
Factorial f = new Factorial () ;
System.out. println (“ Factorial of 3 is ” + f.fact (3) )  ;
System.out. println (“ Factorial of 4 is ” + f.fact (4) );
System.out. println (“ Factorial of 5 is ” + f.fact (5) );
}
}

Output

The output from this program is shown here :

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Description –

For those who are unfamiliar with recursive methods, the operation of fact( ) may seem a bit confusing. Here is how it works. When fact( ) is called with an argument of 1, the function returns 1 ; otherwise, it returns the product of fact(n-1) * n. To evaluate this expression, fact( ) is called with n-1. This process repeats until n equals 1 and the calls to the method begin returning. It is basically the use of Recursion.

Content Protection by DMCA.com
Recommended Post   Methods in Java