user3124200
user3124200

Reputation: 353

Initializing variables in for loops

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

Answers (2)

Joshua Burt
Joshua Burt

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

Dr Phil
Dr Phil

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

Related Questions