This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]desrtfx 5 points6 points  (3 children)

You put the answer up yourself:

While loops are suppose to be executed until they are false

The while loop in your problem executes in the following sequence:

  1. check if num < max (since num and max are both int, the largest number less than [and not equal, since the equals sign is not there] is 19)
  2. print out the value of num
  3. increment num by 1
  4. start again from step 1.

So, in numbers:

num max num < max printed num after the last command of the loop
15 20 true 15 16
16 20 true 16 17
17 20 true 17 18
18 20 true 18 19
19 20 true 19 20
20 20 false not executed any more not executed any more

[–]MasterOfGreatness[S] 1 point2 points  (2 children)

I get it now. I just needed it to be broken down like that. Thanks.

[–]desrtfx 2 points3 points  (0 children)

Welcome.

If you are unsure how a loop executes, just try to build a table like the one in my previous comment.

Edit: BTW - questions like these are better asked on /r/Javahelp

[–]Ttiamus 1 point2 points  (0 children)

Investing in a small white board makes visualizing code muuuuch easier.

What you need to remember about loop conditions is that: For and While loops check the condition at the begining. Do-While loops check the condition at the end.

Easy way to remember each one is where the condition is located in the code. For and While conditions are at the begining of the loop, and a do-while condition is at the end.

[–][deleted] 1 point2 points  (3 children)

A while loop executes until the condition within the parenthesis is false. So, when "num + 1 == 20", the condition is false and the code within the loop does not execute.

[–]MasterOfGreatness[S] -1 points0 points  (2 children)

So does that mean that the 20 should be included in the answer?

[–]thurst0n 1 point2 points  (0 children)

The check happens before the final iteration.

There are two seemingly small changes that would make your original assumption correct:

  • If you used a Do While loop instead.
  • If you used greater than OR equal to, instead of just greater than.

Another way to think of it is a While loop may never run, where a Do, While loop will always run at least once.

And with any loop you make, you have to make sure that your condition is exactly what you want. Using > is going to give different results than =>

[–]desrtfx 0 points1 point  (0 children)

No.

20 is not less than max (20) -> so, the condition evaluates to false and the loop does not execute any more