CPA-21-02 practice question 18 of 35

What happens when you attempt to compile and run the following code? #include using namespace std; int main() { int *t; t = new int[2]; for (int i=0; i

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

The code dynamically allocates an array of two integers using new int[2]. A for loop iterates twice (for i=0 and i=1), initializing both elements of the array to 0. Finally, it prints the value at index 1 (t[1]), which is 0. The code is syntactically correct, manages memory (though it leaks since delete[] is missing, it does not prevent execution), and executes without errors.

Why Incorrect

B: Incorrect because the value assigned to t[1] during the loop is 0, not 1. C: Incorrect because the value assigned to t[1] during the loop is 0, not 2. D: Incorrect because the value assigned to t[1] during the loop is 0, not 3.

References

- ISO/IEC 14882:2014 (C++14 Standard), Section 5.3.4 [expr.new] (Dynamic memory allocation).

- ISO/IEC 14882:2014 (C++14 Standard), Section 6.5.3 [stmt.for] (The for statement).

Scroll to Top