Recursion in Java

Java support Recursion function. Recursion is the attribute that allows a method to callitself. A method that calls itself is said to be recusive. The best example of recursion is the computation of the factorial(1*2*3*4*5) of a number. The factorial of a number n(any last number) is the product(*) of all the whole numbers between 1 and n.

 

class Factoriall

{

int factt(int nn)

{

int resultt;

if(nn==1)

return 1;

resultt=factt(nn-1)*nn;

return resultt;

}

}

class Recursionn

{

public static void main(String aa[])

{

Factoriall fac=new Factoriall();

System.out.println("Factorial of 3...."+fac.factt(3));

System.out.println("Factorial of 4...."+fac.factt(4));

System.out.println("Factorial of 5...."+fac.factt(5));

System.out.println("Factorial of 6...."+fac.factt(6));

System.out.println("Factorial of 7...."+fac.factt(7));

}

}

Recursion in Java

Explanation…

When factt()method is called with an argument of 1, the function returns 1; otherwise it returns the products of fact(nn-1)*nn(factorial calculation). To evaluate this expression, factt() is called with nn-1(decrement). This process repeats until nn equals 1(nn=1) and the calls to the method begin returning.