Skip to main content

Find Factorial of a number using Recursion

Program : Factorial Using Recursion
class Factorial{

public static void main(String args[]){
int number = Integer.parseInt(args[0]);
System.out.println("Factorial of " + number + " = " + factorial(number));
}

public static int factorial(int n){

// Check if the number is greater than equal to 0.
// because factorial of a number < 0 is undefined.

if(n == 1)
return 1;

return n * factorial(n-1);

}

}
Factorial of 5 = 120

Here the function factorial for
  • number =1 will return  1
  • number =2 will return  2 * factorial(1)  = 2 * 1 = 2
  • number =3 will return  3 * factorial(2)  = 3 * 2 * factorial(1) =  3 * 2 * 1 = 6

Comments