Drills: check yourself
Answer yourself first, only then open the answer.
1. What does this program print?
void double_it(int x) {
x = x * 2;
}
int main(void) {
int a = 5;
double_it(a);
printf("%d\n", a);
return 0;
}
Answer
5
double_it gets a copy of a. It doubles its own x, and a stays 5.
2. What do you fix?
main.c: In function 'has_passed':
main.c:5:1: error: control reaches end of non-void function [-Werror=return-type]
5 | }
| ^
int has_passed(int grade) {
if (grade >= 5) {
return 1;
}
}
Answer
When grade < 5, the function reaches its end without a return. It needs return 0; after the if. Or the whole function in one line: return grade >= 5;.
3. How many times in all is fib called when main calls fib(4)?
int fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
Answer
9 times: fib(4) once, fib(3) once, fib(2) twice, fib(1) 3 times, fib(0) twice. The same value is computed several times, so fib(40) takes a noticeable time. A loop does the same in 40 steps.
4. Write the contract and the assert for a function that returns what percentage part is of whole, e.g. 3 of 4 → 75.0.
double percent(int part, int whole)
Answer
/* What percentage part is of whole.
Before: whole > 0, 0 <= part <= whole.
After: a value from 0 to 100. */
double percent(int part, int whole) {
assert(whole > 0 && part >= 0 && part <= whole);
return 100.0 * part / whole;
}
whole > 0 guards against division by 0. Without 100.0 it would be integer division.
5. What does bounce(3) print?
void bounce(int n) {
if (n == 0) {
return;
}
printf("%d ", n);
bounce(n - 1);
printf("%d ", n);
}
Answer
3 2 1 1 2 3
The first printf runs on the way down (3, 2, 1), the second on the way back, once the inner call has finished (1, 2, 3).