CS U111 · Lecture 10 · drill
Recursion: predict the output
Six short recursive programs per sheet, freshly generated each time. Write exactly what each one prints, then reveal: the real output, the winding-and-unwinding trace (or the call tree), and the one rule the program was testing. A sheet takes about fifteen minutes.
Every program is complete except for the #include <stdio.h> line at the top. Trace on paper first. For a one-call function, write the calls going down in a column, then the returned values coming back up next to them. For a two-call function, draw the tree. Then type the output into the box exactly. If the program prints several lines, press Enter between them, or type ⏎. Extra spaces don't count against you. Reveal marks each answer. Open See the method to get the trace and the rule. If the idea itself is shaky, read the recursion lesson first; the recursion notes have the one-page summary.
The mid-sem covers the lectures "until recursion" for breadth, so expect recursion as short tracing questions rather than long programs. Every family here comes from a slide in Lecture 10: factorial and power, the winding/unwinding print (confusingPrint), the Fibonacci tree and its repeated calls, isEven/isOdd, tail recursion with an accumulator, missing or non-converging base cases, and the activity's mystery and digitSum. Slide 21 (recursion on arrays) is excluded from the mid-sem, so nothing here passes an array.
R1. A recursive call pauses the current frame until the smaller call answers. The work written around the call (n * …, n + …) happens on the way back up. Every frame has its own n, so nothing is overwritten.
R2. Code before the recursive call runs while winding (in call order). Code after it runs while unwinding (reverse order, deepest call first).
R3. n % 10 is the last digit and n / 10 drops it. Whether the digits print back to front or in order depends only on whether the print comes before or after the call.
R4. Two recursive calls make a tree. C finishes the whole left call before starting the right one. A counter incremented on entry counts every node of the tree, base calls included.
R5. Mutual recursion: two functions call each other, each time with a smaller argument. The function that is holding the call when the base case is reached decides the answer. Prototypes let each one call the other before it is defined.
R6. Tail recursion: the call is the last thing the function does, and the running answer travels down in the accumulator. The base case returns the accumulator; the frames above just pass it up.
R7. A base case only helps if every call moves toward it. Overshooting an == test or moving away from it means the frames pile up until the stack overflows and the program crashes.
R8. n % 2 and n / 2 peel off binary digits. cond ? a : b can hold a base case and a recursive case in one return.