Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the factorial of a given number.

Java Code Example — Simple Programs

ADVERTISEMENT

Java Program to find the factorial of a given number.

Objective

Write a Java program to calculate the factorial of a user-provided integer.

Algorithm / Approach

  1. Prompt the user to input a positive integer n.
  2. Initialize an integer variable res to 1 (this will store the result).
  3. Start a for loop from i = n down to 2.
  4. In each iteration, multiply res by i (res = res * i).
  5. After the loop completes, print res.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  int n,res=1;
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num: ");
  n = s.nextInt();
  for(int i=n; i>=2;i--) {
   res = res*i;
  }
  System.out.print("Result = "+res);
 }
}

Expected Output

Enter a Num: 5
Result = 120

Explanation of the Program

  • The factorial of a number N (denoted as N!) is the product of all positive integers less than or equal to N.
  • The loop decrements from n down to 2, repeatedly multiplying the running total.
  • We can stop at 2 because multiplying by 1 does not change the result.
  • The res variable must be initialized to 1. If it were initialized to 0, every multiplication would yield 0.

Complexity

Time Complexity O(n) - The loop runs n times.
Space Complexity O(1)

Common Mistakes

  • Initializing the result variable res to 0 instead of 1.
  • Not handling inputs of 0 (since 0! = 1, the loop condition fails, and it correctly prints the initialized value 1).
ADVERTISEMENT