PKM357 - 7 months ago 10
Java Question

# Nested loop clarification - Edited

I'm an intro Java student, and I'm studying for a final exam. I'm going over a prior quiz on repetition statement loops, and see an answer I got wrong and cannot figure out for the life of me why the answer is the way it is.

Can someone please tell me why

`z = 29`
in the following case (and not
`25`
)? My Professor marked it wrong saying it was
`29`
but without explanation.

``````int z = 0;
for(int x=0; x<5;x++){
for(int y=0; y<5;y++){
z++;
}
z++;
}

z--;
``````

The only way I was able to get
`29`
was by the inner loop executing
`5`
times (same for outer loop therefore,
`5*5=25`
plus 4?? Also I've executed this in my IDE and the console printed this when I tried
`system.out.println(z);`

``````4
8
12
16
20
``````

(so I'm now fairly confused) Any assistance you could provide would be greatly appreciated.

``````int z = 0;
for(int x=0; x<5;x++){
for(int y=0; y<5;y++){
z++;
}
z++;
}
z--;
``````

Indeed results in `z` being equal to `29`. Lets calculate the difference for `z` for each part. The inner `for` loop iterates five times for each iteration of the outer loop so:

``````for(int y=0; y<5;y++){
z++;
}
``````

is basically equal to:

``````z += 5;
``````

We thus rewrite the program to:

```int z = 0;
for(int x=0; x<5;x++){
z += 5;
z++;
}
z--;
```

Now `z += 5;` and `z++` is equal to `z += 6;`. We rewrite the program to:

```int z = 0;
for(int x=0; x<5;x++){
z += 6;
}
z--;
```

The `for` loop is again repeated five times so the update for `z` is: `z += 5*6;` or `z += 30;`. We rewrite the program to:

```int z = 0;
z += 30;
z--;
```

Finally we merge the three statements into one: `int z = 0+30-1;` or

```int z = 29;
```
Source (Stackoverflow)