Saturday, October 18, 2025

Nitheen Kumar

Write a Java program to Find Factorial of a Number

Interview Question

Q: Write a Java program to find the factorial of a given number.?


The factorial of a number n is the product of all positive integers from 1 to n.

Formula:

Write a Java program to Find Factorial of a Number
n! = n × (n-1) × (n-2) × ... × 1


Example:


5! = 5 × 4 × 3 × 2 × 1 = 120


Java Program: Factorial of a Number


import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        long fact = 1;

        // Loop to calculate factorial
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        }

        System.out.println("Factorial of " + n + " is: " + fact);
        sc.close();
    }
}

🔍 Explanation

  1. Input: User enters a number.

  2. Loop: A for loop multiplies numbers from 1 to n.

  3. Variable: fact stores the ongoing product (initialized as 1).

  4. Output: Displays the factorial result.


⚙️ Example Output

Enter a number: 5
Factorial of 5 is: 120


Subscribe to get more Posts :