What will be the output of the following code? #include <iostream> using…
2025
What will be the output of the following code?
#include <iostream>
using namespace std;
int main ()
{
int x = 0, y = 1;
for (; y; cout << ++x << y++ << " ")
{
x = y++ <= 15;
}
return 0;
}- A.
31,71,41,60,21
- B.
22 23 44 55
- C.
21 31 51 61
- D.
Infinite loop
Show answer & explanation
Correct answer: D
A C++ `for (init; cond; incr)` loop re-checks `cond` before every pass, runs the loop body only while `cond` is non-zero, and always runs `incr` right after the body — so the loop keeps running for as long as `cond` never becomes 0, no matter how many values get printed along the way.
`x = 0, y = 1` initially; the loop's condition is simply `y`, so it runs as long as `y != 0`.
On every pass, the body executes `x = y++ <= 15;` first — this compares the current `y` to 15, then increments `y` by 1 regardless of the comparison's result.
The loop's own increment clause then runs `cout << ++x << y++ << " "` — this increments `x` before printing it, then prints and increments `y` a second time in the very same pass.
For the first several passes `y` is still ≤ 15, so `x` is set to 1 in the body; once `y` climbs past 15 (which happens quickly, since it grows by 2 every pass), the body instead sets `x` to 0 on every remaining pass.
From that point on, only `y` keeps changing: it is unconditionally incremented once in the body and once in the increment clause, so it grows by exactly 2 on every pass with no code path that ever decreases it.
Because `y` only ever increases from a positive value by steps of 2, it can never return to 0, so `cond` (`y`) never becomes false and the `for` loop never exits — it keeps printing new x/y value pairs forever.
Independently: nowhere in the loop does any statement subtract from `y` or reset it — both occurrences of `y++` are unconditional post-increments, so from the point `y` exceeds 15 it stays odd forever (odd + 2 + 2 + ... is always odd) for as long as the program stays within defined 32-bit signed-int behavior. Only an eventual signed-integer overflow — which is itself undefined behavior in standard C++, and would take on the order of a billion further passes to reach — could interrupt this; every reachable, well-defined code path only ever increments `y`, so for the question's intended output the loop never terminates.