CODE
class FactorialUsingRecursion
{
public static void main(String s[])
{
System.out.println("Factorial of 5 is " + factorial(5) );
}
public static int factorial(int i)
{
if( i == 1 ) // LINE A
{
return 1;
}
return i * factorial(i - 1); // LINE B
}
}
Factorial of 5 is 120
The method factorial defined here is a recursive method. As we can see at LINE B, it is calling itself. It also has a condition in LINE A. When this condition is true, it will not call itself, hence stopping the recursive calls.
As we know the factorial of any number is the product of all the numbers before it. We know factorial of n is
LINE A
, it will not call the method again and simply returns 1
.
i
value is 1, the factorials will be calculated, as shown below.