What is the output of the following snippet? #include <iostream> using namespace std; int main() { int *it[3]; for(int i = 0; i < 3; i++) { it[i] = new int [i + 1]; for(int j = 0; j < i + 1; j++) it[i][j] = 10 * i + j; } cout << it[2][2]; for(int i = 0; i < 3; i++) delete [] it[i]; } 22 11 33 Compilation fails
Question
What is the output of the following snippet?
#include <iostream>
using namespace std;
int main() { int *it[3];
for(int i = 0; i < 3; i++) {
it[i] = new int [i + 1];
for(int j = 0; j < i + 1; j++)
it[i][j] = 10 * i + j;
}
cout << it[2][2];
for(int i = 0; i < 3; i++)
delete [] it[i];
}
22
11
33
Compilation fails
Solution
The output of the given C++ code snippet will be 22.
Here's the step by step explanation:
-
The code declares an array of integer pointers
it[3]. -
Then, it enters a loop that iterates three times (i = 0, 1, 2).
-
In each iteration, it allocates a dynamic array of integers of size
i + 1and assigns its address toit[i]. -
Then, it enters another loop that iterates
i + 1times and assigns the value10 * i + jto each element of the dynamic array. -
After the loops, it prints the value of the third element of the third dynamic array, which is
10 * 2 + 2 = 22. -
Finally, it deallocates the dynamic arrays.
So, the correct answer is 22.
Similar Questions
What is the output for the following code?
What does the following code snippet do?
What is the output of the following code in Python?
What is the output for the following code?Note: This question helps in clearing conceptual technical interviews for service-based companies.
What will be the output of the following PHP code?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.