How to Write a Java Program to Find the Factorial of a Number ( Recursive method Included )

The factorial of a positive integer n, which is denoted as n!, is the product of all positive integers less than or equal to n.

That is n! = n * (n-1)*(n-2)*....*3*2*1

So 4! = 4 * 3 * 2 * 1 which is equal to 24.

Factorial for the numbers 0 and 1 is 1. That is 0! = 1 and 1! = 1. For negative numbers factorial value doesnt exists.

We can write this program using the iterative and the Recursive method.

Here we have both programs for you.

Java Program to Find the Factorial of a Number using Iterative Method

 1 package example;
 2 import java.math.BigInteger;
 3 
 4 public class Factorial {
 5     public static void main(String[] args) {        
 6         int number = 4, factorial = 1;    
 7         if( number < 0 )
 8             System.out.println("Cant fond the factorial of negative number");
 9         else if ( number <= 1 )
10             System.out.printf("%d! = %d",number,factorial);
11         else {
12             for( int counter = number; counter >= 2; counter-- ) {
13                 factorial = factorial * counter;
14             }
15             System.out.printf("%d! = %d",number,factorial);
16         }
17     }
18 }

Watch this Video and Learn to write a Java Program to Find the Factorial of a Large Number using Iterative Method

Java Program to Find the Factorial of a Number using Recursive Method

 1 package exampleProgram;
 2 import java.util.Scanner;
 3 public class Factorial {
 4     
 5     static int factorial(int n) {
 6         if ( n <= 1 )
 7             return 1;
 8         
 9         return n * factorial(n-1);
10     }
11 
12     public static void main(String[] args) {
13         int number,result;
14         Scanner input = new Scanner(System.in);
15         System.out.println("Enter the non negative number");
16         number = input.nextInt();
17         input.close();
18         
19         result = factorial(number);
20         
21         System.out.printf("%d! = %d",number,result);
22     }
23 
24 }

Watch this Video and Learn to write a Java Program to Find the Factorial of a Large Number using Recursive Method