Search code examples
javafor-loopfactorial

Why for loop is iterating more than given condition in my Java program


I am trying to find factorize of an integer with for loop(with number of iteration) but the output is more than the specified number of loops.

I write the same code on my laptop but there it is working fine with specific number of iteration and not exceeding.

public class Test {
    public static void main(String args[]) {
        int n=5;
        for(int a=1; a<=n; a++ ) {
            n=a*n;
            System.out.println(n);
        }
    }
}

Output

5
10
30
120
600
3600
25200
201600
1814400
18144000
199584000
-1899959296

Solution

  • I guess you are looking for something like:

    1*n = n
    2*n = 2n
    
    ... ... ...
    
    (n-1)*n = n(n-1)
    n*n = n^2
    

    So, partial result is like, a*n where n is fixed and a is increasing by 1 till n. In your code, you put n=a*n which is meaning that your n is updating on each iteration. Do not update the value of n that is remove the line which contain n=a*n. Actually, you do not require a counter variable too. Just print the value of a*n into the print statement. Therefore, the solution could be

    public class Test {
        public static void main(String args[]) {
            int n=5;
            for(int a=1; a<=n; a++ ) {
                System.out.println(a*n);
            }
        }
    }