can someone explain how this code ends up with i = 5
i just dont see it.
Ive tried messing around with it and noticed that when I change i to 4 the while statement will be while(4/5) and the loop wont execute. another thing ive noticed is that if i change i to anything 5 and above it counts down to 5 statrting from i.
i know why it counts down which is because of the "i--" but i dont know what is exactly making the statement true or not true if that makes any sense
In boolean context, 0 is false and non-zero (1, 42, -13) is true.
Also, integer division truncates any fractional result, so 4/5 == 0 and 6/5 == 1.
Finally, although i-- decrements i, it evalutates to the old value before the decrement. So when i is 5, it "returns" 5 but sets i to 4.
So in the code as given, 5/5 is 1, which is true, so the body of the while loop executes, which prints 5 and decrements i to 4. Then the while test is evaluated again, but 4/5 is 0 which is false, so the loop stops.
Hello COOGSHOUSE713,
the expression i / 5 evaluate to an integer because of the prior int i = 5;
The result will be 5 divided by 5 equals 1.
If i becomes a 4, the division ( 4 divided by 5 ) becomes a zero followed by decimals and the decimals are lost because an integer has no decimals.
So, 4 / 5 evaluates to zero ( or false ), which is why the loop only iterates once.
Hope this helps.