Questions 7–12
7. How many stars does it print?
for (int j = 1; j < 20; j *= 3) {
printf("*");
}
Answer
j: 1, 3, 9, and 27 no longer satisfiesj < 20. When the step isn'tj++, write the values in a row and count. (Topic 3)
8. You tidied a colleague's code with Reformat Code and fixed one bug in it. How many commits?
Answer
Two: first Reformat Code, then the fix. That way the fix's diff shows one changed line, not the whole rewritten file. (Topic 4)
9. What does f(6) return? And f(5)?
int f(int n) {
if (n == 0) {
return 0;
}
return n + f(n - 2);
}
Answer
f(6) = 6 + 4 + 2 + 0 = 12. f(5) never reaches 0: 5, 3, 1, -1, -3… The function calls itself without end until the stack runs out (stack overflow), and the program crashes. It is missing the contract assert(n >= 0 && n % 2 == 0) or the condition n <= 0. (Topic 5)
10. What is wrong?
int age = read_int("Age: ");
assert(age >= 0);
Answer
assert checks the programmer's mistakes, not the user's input. In a Release build (NDEBUG) the assert disappears, and a negative age gets through. Check input with a while loop and ask again. (Topic 5)
11. What does it print?
int m[4] = {4, 3, 2, 1};
for (int x = 0; x < 4; x++) {
m[x] = m[3 - x];
}
printf("%d %d %d %d\n", m[0], m[1], m[2], m[3]);
Answer
1 2 2 1
Not 1 2 3 4: when x = 2, m[1] has already been overwritten (2), so m[2] = m[1] = 2, and when x = 3, m[0] is already 1. To reverse an array, swap pairs with a temporary variable and only up to the middle. (Topic 6)
12. An array holds 100 sorted numbers. At most how many boxes does binary search check?
Answer
7: 100 → 50 → 25 → 12 → 6 → 3 → 1. Put another way: 2⁷ = 128 is the first power of two greater than 100. Linear search would check all 100 in the worst case. (Topic 6)