Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
read it out loud, it helps, while bigger than 0 do minus 3, so it does:
12
9
6
3
0
then it exits because 0 isn't bigger than 0 -
While the number is greater than zero, subtract 3 from it
So it will run 5 times (15/3=5)
At the end (after the while loop) the number has a value of 0, because you subtracted 3 from it, 5 times (15-3-3-3-3-3=0) -
@lmute
that hair or scratch on your monitor is really disturbing though, so maybe remove that if its not physical damage 😅 -
goodJVM11077y@Bitwise me too 😅
especially I hate languages like python where indentation is a part of the semantics of the language -
@jaydevs SO will give you -8 for posting this. And the first comment will read "we do not do homework" or something like that.
-
Well since non of the options is infinite loop and there are no negative numbers in the answer options, answer is 0, got my two grades and pass the exam 😀
Just how I think in exam no need to be nerdy and ask why happens -
It would be 13 if it weren't a loop.
Not knowing how "imaginary" brackets work as a beginner can be a bit frustrating and confusing.
So your code really looks like this
int num = 15;
while ( num > 0 )
{
num = num - 3;
}
System.out.println(num);
In most modern languages (assuming this is probably C, C# or Java), its kind of allowed to just write an if(), a while or for without brackets if its just ONE line of code that gets repeated. You can see the syntax checker questioning your code sometimes if theres a line of code below "imaginary brackets" .
But the big giveaway here is the spacing. Do you see that num = num - 3 is tabbed to the right?
Most IDEs do that for you when you write a while, if or for above it. (also else if, else, you get the idea)
Its an indicator that its a loop for just ONE line.
If it would be an if(num > 0) num = num - 3; It would be 12, since if's do not loop. -
nukasev4857yThat's what you get when you don't use curly braces in while-loops. At least for me non-curled variants do not register as proper loops in my brain, instead I see it first as a statement that is run only once. I have to do some gazing before my brain registers that there is a loop.
TL;DR: use curly braces for readability. And yes, I'm this zealous on this matter. :)
Related Rants
Can anyone tell me exactly why this is equal to zero?
question
help
java
rookie
newbie