Monday, 20 January 2014

RECURSION IN JAVA

Recursion:


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 recursiveEvery recursion should have some characteristics.That is a simple base case which we have a solution for and a return value and a way of getting our problem closer to the base case. I.e. a way to chop out part of the problem to get a somewhat simpler problem and  a recursive call which passes the simpler problem back into the method.When a method calls itself,
new local variables and parameters are allocated storage on the stack, and the method code is executed with these new variables from the start.Many recursive calls to a method could cause a stack overrun.


Example for recursion

// A simple example of recursion.
class Factorial 
{
int fact(int n) // this is a recursive method
{
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));
}
}

The output from this program is shown here:

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

No comments:

Post a Comment