Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Multi For Loop Question

Tariq Ab
Greenhorn
Posts: 14
Here is the output:

0 4
0 3
1 4
1 3
3 4
3 3

Why do the right side (X) repeat itself twice? Shouldn't the second value of x be 3?
This is how i came to this conclusion: When X leaves the for loop for the first time, it gets incremented to 1. Then it enters the If statement, which increments the X value to X ( ok now im confused
As for the left side (Y) I understand as far as the second output, but why does it output 4 again?

Thank you

Matthew Brown
Bartender
Posts: 4565
8
I'm slightly confused by your expanation, because X is the left side and Y is the right side according to that code.

Anyway...

- Each y loop starts at 4 and reduces y until y is 2 - so it will output 4 and 3 on each loop.

- The x loop would count 0, 1, 2, 3, but because of the if statement it skips 2, and so counts 0, 1, 3.

Put them together, and you get the output you've given. Does that make sense?

Tariq Ab
Greenhorn
Posts: 14

I accidently mixed up the left and right sides

I understand it a little better now. I got why Y keeps repeating 3-4-3-4.
But I'm still not sure about X. I know I'm missing something, Its probably stupid but why does it repeat twice before each increment

Matthew Brown
Bartender
Posts: 4565
8
• 1
Because you've got one loop inside another. For every value of x, y runs through its entire loop. y goes through 2 values (4 and 3) each time, which is why you see each x value twice.

Tariq Ab
Greenhorn
Posts: 14
Got It!

with your explaination and this sample code, I was able to fully understand this concept

http://mathbits.com/mathbits/java/looping/nestedfor.htm

Thanks again