Reputation: 353
If I type in the code with the word "test" then the word "test" prints out 9 times (as intended). If I type in the code with the word "test 2", "test 2" only prints out 3 times. Why is this (why does it print out 3 times, and not 9 times)?
for (int a1 = 3; a1 > 0; a1--) {
for (int a0 = 3; a0 > 0; a0--) {
System.out.println("test");
}
}
// Second version of code below
int a1 = 3;
int a0 = 3;
for (; a1 > 0; a1--) {
for (; a0 > 0; a0--) {
System.out.println("test 2");
}
}
Upvotes: 0
Views: 50
Reputation: 76
Formatted better:
for (int a1=3;a1>0;a1--)
{
for (int a0=3;a0>0;a0--)
{
System.out.println("test");
}
}
//Second version of code below
int a1=3;
int a0=3;
for (;a1>0;a1--)
{
for (;a0>0;a0--)
{
System.out.println("test 2");
}
}
Essentially the issue you are having is because in your second example, you are declaring and instantiating the variables outside of the for loop. So when the nested loop finishes, it goes back to the outer loop. But a1 will not re-instantiate after the nested loop, and such a1's value is already 0, skipping the loop.
Upvotes: 1
Reputation: 880
The two pieces of code are not equivalent. Your control variable of the inner loop has to be initialized on each (outer) iteration. So the equivalent code will be:
int a1 = 3;
for (; a1 > 0; a1--) {
int a0 = 3;
for (; a0 > 0; a0--) {
System.out.println("test 2");
}
}
Upvotes: 3