• Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested For Loop Help  RSS feed

 
Adam Scott
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, this is my first post on coderanch. I'm using Head First Java 2nd ed right now and this problem is from chapter 5. I'm having trouble understanding why this code outputs what it does. I see why it outputs "0 4" on the first loop, but why isn't it "1 3" on the second loop? I'm pretty much stuck at that point. Thanks in advanced.


 
Knute Snortum
Sheriff
Posts: 4288
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

Ask yourself, how many times does the inner loop execute before it passes control back to the outer loop? What is the value of x during this?
 
Anindya Roy
Ranch Hand
Posts: 76
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Debug the code in any IDE like Eclipse, Netbeans, Intellija etc. to see how it works
 
Varun Selva
Ranch Hand
Posts: 48
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


here x will be increase by one on next attempt only.

because x++ mean, post increment.
end of the every cycle, will increase.

Hope, you will understand.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

That question has come up before. What you should do is get a pencil and write down the number of loops. Somebody else tried that here. Follow the same procedure and maybe you will get the same results
 
Adam Scott
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow so many different ways to figure it out. Thanks guys I'll try all of your methods.

Edit: Looks like I missed that the inner for loop loops. Problem solved.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
I still prefer pencil and paper because it forces some of the information to go where it really needs to: your brain
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!