Explanation:sizeof(a) is the whole array's size 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 run from a[0] to a[2]). C does not flag a compile error, but the read is undefined behavior — anything can happen, and it's a classic source of security bugs.
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. This is the standard pattern for summing every element of an array with a for loop.
Explanation: When the initializer list is shorter than the array size, the remaining elements are zero-filled.
a[0]=1, a[1]=2 (explicitly set)
a[2], a[3], a[4] are automatically 0
This is also why the idiom int a[5] = {0}; zero-initializes every element.
Question 6 — Modifying an array
int a[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
a[i] *= 2;
}
printf("%d\n", a[3]);
What does this print?
4
8
6
10
Explanation: The loop doubles every element.
Original: {1, 2, 3, 4, 5}
After doubling: {2, 4, 6, 8, 10}
a[3] = 4 × 2 = 8
You can modify any array element with a[i] = value.
Question 7 — sizeof returns total bytes
// Assume int is 4 bytesint a[10];
printf("%d\n", (int)sizeof(a));
What does this print?
10
40
4
8
Explanation:sizeof(array) returns the total size in bytes of the array.
Size of one element: sizeof(int) = 4 bytes
Number of elements: 10
Total: 4 × 10 = 40 bytes
Note: when you pass an array to a function, it "decays" to a pointer, so sizeof returns the size of a pointer instead (typically 8). If you need the element count inside the function, pass it as a separate argument.