File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multi For Loop Question

 
Tariq Ab
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your reply!

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: 4549
8
Java Netbeans IDE Scala
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic