Challenge - 5 Problems
Multi-dimensional arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of nested loop accessing 2D array
What is the output of the following C++ code?
C++
#include <iostream> int main() { int arr[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { std::cout << arr[i][j] << " "; } } return 0; }
Attempts:
2 left
💡 Hint
Think about how the nested loops iterate rows then columns.
✗ Incorrect
The outer loop goes through rows (0 and 1), and the inner loop goes through columns (0 to 2). So it prints all elements in row 0, then all in row 1.
❓ Predict Output
intermediateValue of element after assignment in 3D array
What is the value of
arr[1][0][2] after running this code?C++
#include <iostream> int main() { int arr[2][2][3] = {{{1,2,3},{4,5,6}}, {{7,8,9},{10,11,12}}}; arr[1][0][2] = arr[0][1][1] + arr[1][1][0]; std::cout << arr[1][0][2]; return 0; }
Attempts:
2 left
💡 Hint
Check the values at arr[0][1][1] and arr[1][1][0] and add them.
✗ Incorrect
arr[0][1][1] is 5 and arr[1][1][0] is 10, so 5 + 10 = 15.
🔧 Debug
advancedIdentify the error in 2D array initialization
What error will this code produce?
C++
#include <iostream> int main() { int arr[2][2] = {1, 2, 3, 4, 5}; std::cout << arr[1][1]; return 0; }
Attempts:
2 left
💡 Hint
Check how many values are allowed for a 2x2 array.
✗ Incorrect
The array size is 2x2=4 but 5 values are given, causing a compilation error.
❓ Predict Output
advancedSum of elements in jagged 2D array simulation
What is the output of this code simulating a jagged array using pointers?
C++
#include <iostream> int main() { int row1[] = {1, 2}; int row2[] = {3, 4, 5}; int* arr[2] = {row1, row2}; int sizes[2] = {2, 3}; int sum = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < sizes[i]; j++) { sum += arr[i][j]; } } std::cout << sum; return 0; }
Attempts:
2 left
💡 Hint
Add all elements in both rows carefully.
✗ Incorrect
Sum is 1+2+3+4+5 = 15.
🧠 Conceptual
expertMemory layout of multi-dimensional arrays
In C++, how are multi-dimensional arrays stored in memory?
Attempts:
2 left
💡 Hint
Think about how arrays are laid out in C++ standard.
✗ Incorrect
C++ stores multi-dimensional arrays in row-major order, meaning all elements of a row are stored next to each other in memory.
