简体   繁体   中英

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

You are changing the value of n in the loop, so it iterates more. Use another variable to count loops, eg

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

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);
        }
    }
}

//Thanks for your responses with your help i was able to figure out the issue //This is how i over come the problem to limit the iteration/

public class Test {
public static void main(String args[]) {
    int n=5;
    int counter=n;

    for(int a=1; a<=counter; a++ ) {
        n=a*n;
    System.out.println(n);
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM