MeshWorld India LogoMeshWorld.
ProgramJAVA2 min read

Factorial of a Number Using For Loop in Java: Code & Algorithm

Vishnu
By Vishnu
Factorial of a Number Using For Loop in Java: Code & Algorithm

A program to find factorial for an integer data-type using for loop in JAVA

Algorithm for Factorial

Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, result = 1
Step 4: if i <= n go to Step 4 otherwise go to Step 7
Step 5: Calculate result = result * i
Step 6: Increment the i by 1 (i = i + 1) and go to Step 3
Step 7: Display result
Step 8: Stop


As 1 is an identity for multiplication i.e whenever any number is multiply with 1, same value is obtained. For e.g 7 * 1 = 7 Thats why we assign result = 1 as initial value

Working example

/**
 * Factorial for N using FOR loop
 */
class FactorialDemoUsingForLoop
{
    public static void main(String[] args)
    {
        int i, result = 1, n = 5;

        for (i = 1; i <= n; i += 1)
        {
            // System.out.println("I: " + i);
            // System.out.println("Result B4: " + result);
            result *= i;
            // System.out.println("Result After: "+ result);
        }

        System.out.println("Factorial of " + n + ": " + result);
    }
}

Output for number 5

Factorial of 5: 120
Share_This Twitter / X
Vishnu
Written By

Vishnu

Founder & Principal Architect at MeshWorld. Senior engineer and instructor specializing in AI agent systems, scalable web architecture, and modern development workflows.

Enjoyed this article?

Support MeshWorld and help us create more technical content