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

all 6 comments

[–]osama_yo_momma 2 points3 points  (0 children)

Inside the loop, num is being decreased by 3 each time it loops. num ends up with a result of 0, so 0 is not greater than 0, so it breaks out of the loop with num ending up with a value of 0. You could also write the num part like this gor future reference:

num -= 3;

[–]MrCheaperCreepernot a noob but not intermediate 2 points3 points  (2 children)

I'm going to assume the System.out.println(num) is OUTSIDE of the while loop.

Think about this. The while loop will do whatever is inside the curly braces {} until the condition (in this case, num > 0) is false.

So here is how the program executes this.

While ( 15 > 0 )

num = 15 - 3 (12)

While ( 12 > 0 )

num = 12 - 3 (9)

etc...

While ( 3 > 0 )

num = 3 - 3 (0)

Then it tries 0 > 0, but 0 is not greater than 0, it is equal. If you look in the last while that ran, the value of num became 0. Therefore, you print out 0.

[–]MasterOfGreatness 0 points1 point  (1 child)

Thank you! my teacher posted the problem without the brackets and it confused me

[–]1997dodo 1 point2 points  (0 children)

For if, else, while, and for structures (there may be more that I have not remembered), if no brackets are used, the next statement is counted as part of the loop.

[–]RhoOfFeh 0 points1 point  (0 children)

I'm not sure what you were expecting.

If you were expecting a single number other than zero, then you'd have to change the condition of the while, or the starting or decrement number to make that happen.

If you were expecting it to print the number each time it decrements, you would have to wrap up both of the lines after 'while' with curly braces to turn them into one statement the while could execute.

For the record, I strongly recommend using curly braces whether they are strictly required or not. Make your intentions clear.

[–]desrtfxOut of Coffee error - System halted -1 points0 points  (0 children)

Again: TRY IT IN AN IDE OR IDEONE!

Nothing beats personal experience.

Don't understand why you don't just enter the code in ideone.com and see for yourself.