CPA-21-02 practice question 1 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; int main(){ int i, j; for(i = 0, j = 1; j < 2, i < 4; i++, j++); cout

Full set: 257 questions
Answer options
A: It prints: 4 5 Correct answer
B: It prints: 2 3
C: It prints: 3 2
D: It prints: 4 3
Correct Answer:
A. It prints: 4 5
Explanation

The termination condition in the for loop uses the comma operator: j < 2, i < 4. In C++, the comma operator evaluates the left operand, discards its result, and then evaluates and returns the right operand. Therefore, the loop's termination depends entirely on the rightmost expression, i < 4. The loop iterates while i is 0, 1, 2, and 3. During the iteration where i = 3 and j = 4, the increment step executes, resulting in i = 4 and j = 5. The condition i < 4 then evaluates to false, terminating the loop. The final cout statement prints "4 5".

Why Incorrect

B. It prints: 2 3: Incorrect because it assumes the loop terminates when j < 2 becomes false, completely ignoring the standard behavior of the C++ comma operator.
C. It prints: 3 2: Incorrect because it miscalculates both the loop termination condition and the synchronous incrementation of the variables.
D. It prints: 4 3: Incorrect because j increments synchronously with i on every iteration; if i reaches 4, j must reach 5.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 8.19 [expr.comma] (Comma operator).

- MIT OpenCourseWare, 6.096 Introduction to C++, Lecture 2: Control Structures, Section on Operators.

Scroll to Top