Factorial Program Using Recursion in Java

 

Program to find factorial of given number by recursion.

/**
 * This program is used to find factorial of given number by recursion.
 * @author javawithease
 */
public class FactorialByRecursion {
      /**
       * This method is used to find factorial of given no. by recursion.
       * @param num
       * @return int
       */
      static int fact(int num){
            //Factorial of 0 is 1.
            if (num == 0)
                  return 1;
            else
                  return num * fact(num-1);
      }     
 
      public static void main(String args[]){
            int num = 5, factorial;
            //method call
            if(num > 0){
               factorial = fact(num);
               System.out.println("Factorial of "+num+" is "+ factorial);
            }else{
                  System.out.println("Number should be non negative.");
            }          
      }
}

Output:

Factorial of 5 is 120

Download this example.