factorial of given number in java code example

Example 1: how to make factorial in java

class fact{
	static int fac(int n){
		int ans =1;
		for(int i=1; i<=n; i++){
			ans = ans*i;
		}
		return ans;
	}

	public static void main (String[] args){
		int f = 5;
		System.out.println(fac(f));
	}
}

Example 2: Factorial program in java

// Factorial program using recursion
public class FactorialRecursion
{
   public static void main(String[] args)
   {
      int factorial = 1;
      int number = 6;
      factorial = factorialFunction(number);
      System.out.println("Factorial of " + number + " is : " + factorial);
   }
   static int factorialFunction(int num)
   {
      if(num == 0)
      {
         return 1;
      }
      else
      {
         return(num * factorialFunction(num - 1));
      }
   }
}

Tags:

Java Example