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:
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
-
Input: User enters a number.
-
Loop: A
for
loop multiplies numbers from 1 to n. -
Variable:
fact
stores the ongoing product (initialized as 1). -
Output: Displays the factorial result.
⚙️ Example Output
Enter a number: 5
Factorial of 5 is: 120
Tags: Write a Java program to Find Factorial of a Number