Here is what I understand: the for loop starts, with int i equal to 5 and j equal to 3. Since i > j, it runs the statement (Do While loop). The Do While loop prints the values to the screen. Then since j is equal to 3, it will do the Do While loop again, first decrementing j by 1. So j is 2 and i is 5.. those get printed. Then since j is not >= to 3, the loop ends and backs out to the For loop.
Here is where I am confused. I know that j gets decremented to 1 before it backs to the For loop. I understand everything so far. However, I know that the Do While loop runs again, printing 1 for j and 2 for i. So I gather that since i was greater than j, 3 was subtracted from i... then the Do While ran, printing the new values... and stopped because j isn't >=3. So j becomes zero (though it won't ever print that) but I don't understand how the loop finally ends.
Any hints? I tried looking at code examples in several books but none have that kind of thing.. only ones that talk about when i is less than a value to stop when that boolean is false. However in this code, i so far has always been greater than j.
You start your for loop with i = 5, j = 3, and as you correctly say, the do loop runs twice, leaving j = 1. Then i is reduced by 3, to 2. Then your for loop runs a second time, and you start your do loop. A do loop always runs once, then it tests for its continuation condition. The do loop therefore runs a 3rd time . . . Then, j = 0, and i is reduced again by 3 to -1, so i > j returns false and the for loop terminates.
Joined: Oct 13, 2005
Did you say simple loop?
You now know why you don't use that sort of code in real life!
Joined: May 15, 2008
That makes sense! Thank you so much. =)
subject: Need some help understanding the last portion of this simple loop.