cs-023 — Nested and Confused
| Field | Value |
|---|---|
| id | cs-023 |
| difficulty | Intermediate |
| topics | tracing, nested loops |
| lecture | lecture-06 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | loops, lists, and tracing from lectures 1-6 |
| objective | choose the technique, trace it faithfully, and defend the boundary behaviour |
| solution | held by the instructor; discussed after the attempt |
Problem
Two nested loops with a conditional print. Predict the exact output pattern; then generalise to n lines. Pure trace discipline.
Your deliverable is the exact 4-row pattern, the loop bounds that produce it, and one variant of the inner rule (e.g. star when col > row) that you also trace. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: n = 4 (rows); inner prints star when col <= row else dot
- Output: row1 ''; row2 '.'; row3 '..'; row4 '****...' - each row adds one extra '*' and one extra '.'
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- Trace the inner loop for row 2 by hand FIRST; most wrong answers come from predicting, not tracing.
- Every aggregate here is a small machine: state + update rule.
- The initial value is part of the algorithm, not a detail.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Which accumulator was hardest to get right, and what test would have caught the mistake?"
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: tracing, nested loops.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the plan and trace; finishing the details is a bonus, defending the method is the target.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Construct an input that maximises the trace length and count the steps exactly.