This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with for loops  RSS feed

 
Elim Banda
Ranch Hand
Posts: 46
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im struggling with this code can somebody break it down for me iteration by iteration

 
Fred Kleinschmidt
Bartender
Posts: 560
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the first time through the inner loop (inner = 3), x is incremented (now = 1) and since it is not 2, it is incremented again (now = 2)
The next iteration of inner loop (inner = 2) x is incremented (=3) and since it is not 2, is incremented again (=4)
The inner loop completes, since decrementing inner to 1 and is therefore not > 1.

Outer is incremented (now = 1) and repeat the inner loop. You can follow the above explanation to see that x ends up being 8.

You can walk through it yourself to see that y is decremented 6 times to get a final value of -5.

It would help if you used consistent indentation
 
Carey Brown
Bartender
Posts: 2993
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When in doubt, print it out.
 
Bill foster
Ranch Hand
Posts: 63
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes I like to use debug to see how the program flows, I would trace the steps on paper(include variables) and go through the if statements and for loops.
Sometimes writing the steps on paper slows you do and forces you to think.

I like the print method, that would work for more complex coding and can check if the logic on your paper is correct.

Every time I visit this site I get more ways to understand code, you guys rock!!!

Hope this helps!

Bill
 
Les Morgan
Rancher
Posts: 768
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Elim Banda wrote:Im struggling with this code can somebody break it down for me iteration by iteration


Elim, I think your white space utilization is making tracing a lot harder to do than necessary. I refactored the spacing and added some comments, does this help you trace it out yourself? Bill Foster gave a great piece of insight there: use the debugger to trace what is happening and lookup the values during each step, and Carey Brown's suggestion on adding print's so you can see what is happening is always great.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!