BETA Try the new lesson view
Drills

Drills: check yourself

Answer yourself first, only then open the answer.

1. What does it print?

int a[5] = {1, 2, 3};
int s = 0;
for (int i = 0; i < 5; i++) {
    s += a[i];
}
printf("%d %d\n", a[4], s);
Answer
0 6

The missing boxes a[3] and a[4] get 0, so the sum is 1 + 2 + 3 = 6.

2. Find the bug.

double average(const int t[], int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += t[i];
    }
    return (double)sum / n;
}
Answer

The loop skips t[0] and on its last pass reads t[n], out of bounds. It must be for (int i = 0; i < n; i++). The compiler doesn't warn, and the result is wrong or random.

3. An array holds 16 sorted numbers. At most how many boxes does binary search check?

Answer
  1. Each check halves what is left: 16 → 8 → 4 → 2 → 1, and one more check for the last box. Linear search would check all 16 in the worst case.

4. What is the array after the first step of selection sort (i = 0)?

9 3 7 1 5
Answer
1 3 7 9 5

The smallest is 1 (index 3); it is swapped with t[0], and 9 lands in its place. The other boxes don't move.

5. What does it print?

int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int c = 0; c < 3; c++) {
    for (int r = 0; r < 2; r++) {
        printf("%d ", m[r][c]);
    }
}
Answer
1 4 2 5 3 6 

The outer loop goes over the columns and the inner one over the rows, so the array is printed column by column: 1 4, 2 5, 3 6.