2(v)
How many times will the following loop execute? What value will be returned?
int x = 2;
int y = 50;
do{
++x;
y -= x++;
}
while(x <= 10);
return y;Show SolutionHide Solution↓
The loop will execute 5 times and the value returned is 15.
| Iteration | X | Y | Remark |
|---|---|---|---|
| 2 | 50 | Initial values | |
| 1 | 3 | 47 | x = 4 (3 + 1), y = 47 (50 - 3) |
| 2 | 5 | 42 | x = 6 (5 + 1), y = 42 (47 - 5) |
| 3 | 7 | 35 | x = 8 (7 + 1), y = 35 (42 - 7) |
| 4 | 9 | 26 | x = 10 (8 + 1), y = 26 (35 - 9) |
| 5 | 11 | 15 | x = 12 (11 + 1), y = 15 (26 - 11) |
| 11 | 15 | Condition becomes false. Loop terminates. |