0

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

}
1
  • 2
    After the first outer loop iteration, a0 remains 0 so the inner loop doesn't run any more. Commented Sep 12, 2019 at 23:22

2 Answers 2

3

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

}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.