🇯🇵 日本語 | 🇺🇸 English
Advertisement

Quiz (Arrays)

Test your understanding of array indexing, sizeof, and out-of-bounds access.

Question 1 — Array initialization

int a[5] = {10, 20, 30, 40, 50};
printf("%d\n", a[2]);

What does this print?

20
30
10
Compile error
Explanation: Array indices start at 0. a[0]=10, a[1]=20, a[2]=30.

Question 2 — Number of elements

int a[] = {3, 1, 4, 1, 5, 9};
printf("%lu\n", sizeof(a) / sizeof(a[0]));

What does this print?

4
6
24
1
Explanation: sizeof(a) is the size of the whole array in bytes (24). sizeof(a[0]) is the size of one element (4).
24 / 4 = 6. This is the classic idiom for getting an array's length.

Question 3 — Out-of-bounds access

int a[3] = {10, 20, 30};
printf("%d\n", a[3]);

What happens?

0
30
Compile error
Undefined behavior (garbage value)
Explanation: a[3] is out of range (valid indices are a[0]..a[2]).
C does not raise a compile error, but this is undefined behavior. Anything may happen, and it's a common source of security vulnerabilities.

Question 4 — Sum with a for loop

int a[4] = {2, 4, 6, 8};
int sum = 0;
for (int i = 0; i < 4; i++) {
    sum += a[i];
}
printf("sum = %d\n", sum);

What does this print?

sum = 16
sum = 20
sum = 10
sum = 8
Explanation: 2+4+6+8 = 20. A standard pattern for summing all elements of an array with a for loop.

Result

Please answer the questions
Home