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 questionsThe 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".
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.
- 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.
Keep practicing
Take the free CPA-21-02 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other CPA-21-02 practice questions
- Question 2What happens when you attempt to compile and run the following code? #include #include us…
- Question 3Which of the following statements are correct about an array? int tab[10];
- Question 4What happens when you attempt to compile and run the following code? #include #include us…
- Question 5What is the output of the program if characters 'h', 'e', 'l', 'l' , 'o' and enter are su…
- Question 6What happens when you attempt to compile and run the following code? #include using names…
- Question 7What happens when you attempt to compile and run the following code? #include using names…
