Skip to content

Java Factorial loop

The problem is that the factorial value is updating in a while loop I think that is the problem why. Here is the code

while (true) {
    System.out.print("Enter a positive integer: ");
    n = sc.nextInt();
    if (n > 0) {
        System.out.print(n + "! = ");
        for (int i = 1; i <= n; i++) {
            factorial = factorial * i;
            for (int j = 1; j <= n; j++) {
                if (j == n) System.out.printf("%d", j);
                else System.out.printf("%d x ", j);
            }
            System.out.println("");
            System.out.println("The factorial of " + n + " is " + factorial);
        }
    } else {
        System.out.println("Invalid input");
        break;
    }
}

Okay, so here is the problem when the first input is 5

The factorial of 5 is: 120

But on the second input it goes like this when I tried to input like for example 4

The factorial of 4 is: 2880

it goes higher even though the factorial of 4 is 24

Answer

Just add factorial = 1; after the else block.