I do not understand how the while ((variable)) loop works, when does it end?
1 2 3 4 5 6 7 8 9 10 11
int main()
{
int y = 2;
int x;
while (y)
{
x = 1 + y;
y = y / 2;
cout << x << endl;
}
In this code x will be printed 2 times, so in this case while (y) runs 2 times
But if i change the value of y to let's say 200. The while loop will run 8 times. Could someone please explain? :< Tried to google it but could not find this specific problem
while(y) Executes until y is false. In the case of a boolean this is obvious, but here y is an integer. Implicit int->bool conversion produces false only if the integer is 0. Anything else and the expression is true. Since you're using integer division, any results will be rounded DOWN. So if y < 1, y > 0 it will simply be rounded to 0, and your loop will be false.
The condition expression in the while statement is converted to a bool expression. For conditions of an integral type any value that is not equal to zero is converted to true. Otherwise it is converted to false.
So for the first iteration the value of the expression ( y ) is equal to 2 that is unequal to zero. So it is converted to true. Inside the body of the loop y becomes equal to 1 after the statement y = y/2;
So in the next iteration of the loop the condition expression again is not equal to zero and is converted to true. At this time in the loop body y becomes equal to 0 ( y = 1 / 2 ). So in the next iteration of the loop the condition expression is equal to zero and is converted to false. The loop will not executed any more. Thus the loop was executed two times until y has become equal to zero.
y = 200 //1 times
y = 100 //2
y = 50 //3
y = 25 //4
y = 12 //5, remember int/int acts as div
y = 6 //6
y = 3 //7
y = 1 //8 times
y = 0 // loop terminated