Two Laptop Bag*
The moose likes Beginning Java and the fly likes Need some help understanding the last portion of this simple loop. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need some help understanding the last portion of this simple loop. " Watch "Need some help understanding the last portion of this simple loop. " New topic
Author

Need some help understanding the last portion of this simple loop.

SYD O'Reily
Greenhorn

Joined: May 15, 2008
Posts: 2

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.

What makes the loop end?

Thanks in advance,

SYD
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Welcome to the Ranch, Syd

Always use %n after printf, rather than \n.

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.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
Did you say simple loop?

You now know why you don't use that sort of code in real life!
SYD O'Reily
Greenhorn

Joined: May 15, 2008
Posts: 2
That makes sense! Thank you so much. =)

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need some help understanding the last portion of this simple loop.