CPA-21-02 practice question 2 of 35

What happens when you attempt to compile and run the following code? #include #include using namespace std; int f(int i, int b); int main() { int i=0; i++; for (i=0; i

Full set: 257 questions
Answer options
A: It prints: 202020
B: It prints: 012 Correct answer
C: It prints: 0
D: It prints: 2
Correct Answer:
B. It prints: 012
Explanation

The variable i is initially incremented to 1, but the for loop immediately reinitializes it to 0 via its initialization statement (i=0). The loop condition i<=2 ensures it iterates exactly three times (for i = 0, 1, and 2). In each iteration, the function f(0, i) is called, which returns the sum of its arguments (0 + i). The results (0, 1, and 2) are printed consecutively to the standard output without any spaces, resulting in the output "012".

Why Incorrect

A: The function returns the integer sum of a and b, not a concatenated string or repeated "20"s. C: The loop runs three times, not once, so it prints the results of all three iterations, not just "0". D: The loop prints the results of all three iterations consecutively (0, 1, 2), not just the final iteration's result.

References

- ISO/IEC 14882:2017 (C++17 Standard), Section 9.5.3 [stmt.for], paragraph 1 (for loop execution flow and initialization).

- Stanford University, CS106L Standard C++ Programming, Course Reader (Control Flow).

Scroll to Top