0
0
Cprogramming~20 mins

Two-dimensional arrays in C - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
2D Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested loops filling 2D array
What is the output of this C program that fills a 2D array and prints it?
C
#include <stdio.h>

int main() {
    int arr[2][3];
    int val = 1;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            arr[i][j] = val++;
        }
    }
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    return 0;
}
A1 2 3 4 5 6 \n
B1 3 5 \n2 4 6 \n
C0 1 2 \n3 4 5 \n
D1 2 3 \n4 5 6 \n
Attempts:
2 left
💡 Hint
Look at how the nested loops assign values row by row.
🧠 Conceptual
intermediate
1:30remaining
Memory layout of 2D arrays in C
In C, how is a two-dimensional array like int arr[2][3] stored in memory?
AAs a contiguous block in row-major order (rows stored one after another)
BAs a contiguous block in column-major order (columns stored one after another)
CAs separate blocks for each row scattered in memory
DAs pointers to pointers with each row allocated separately
Attempts:
2 left
💡 Hint
Think about how C stores arrays by default.
🔧 Debug
advanced
1:30remaining
Identify the error in 2D array initialization
What error will this code produce when compiled? int arr[2][3] = { {1, 2}, {3, 4, 5, 6} };
ARuntime error: array index out of bounds
BCompilation error: missing semicolon
CCompilation error: too many initializers for array
DNo error, compiles and runs fine
Attempts:
2 left
💡 Hint
Check the number of elements in each inner initializer list.
📝 Syntax
advanced
1:30remaining
Correct syntax to declare a pointer to 2D array
Which option correctly declares a pointer to a 2D array of integers with 3 columns?
Aint (*ptr)[3];
Bint *ptr[3];
Cint **ptr;
Dint ptr(*)[3];
Attempts:
2 left
💡 Hint
Remember the parentheses placement for pointer to array.
🚀 Application
expert
2:30remaining
Sum of diagonal elements in a square 2D array
Given a 3x3 integer array, which code snippet correctly calculates the sum of the main diagonal elements?
A
int sum = 0;
for (int i = 0; i &lt; 3; i++) {
    sum += arr[i][3 - i];
}
B
int sum = 0;
for (int i = 0; i &lt; 3; i++) {
    sum += arr[i][i];
}
C
int sum = 0;
for (int i = 0; i &lt; 3; i++) {
    sum += arr[3][i];
}
D
int sum = 0;
for (int i = 0; i &lt; 3; i++) {
    sum += arr[i][i + 1];
}
Attempts:
2 left
💡 Hint
Main diagonal elements have equal row and column indices.