Factorial of a Number

This program calculates factorial of a number using for loop.

Problem Statement

Write a Java program that calculates factorial of 5 using a for loop.

Source Code

1 public class Factorial {
2 public static void main(String[] args) {
3 int num = 5;
4 int fact = 1;
5 for(int i=1; i<=num; i++) {
6 fact *= i;
7 }
8 System.out.println("Factorial of " + num + " = " + fact + " - Eduinq");
9 }
10 }

Program Output

Factorial of 5 = 120 - Eduinq

Explanation

The program initializes fact=1. - The for loop multiplies fact by each number from 1 to 5. - After the loop ends, fact holds the factorial value. - This demonstrates how loops can perform repeated multiplication to calculate factorials. Conclusion: Shows how for loop can calculate factorial.

Quick Links to Explore