Splitting a problem before solving it
Top-down design breaks one hard problem into small problems you already know how to solve, and a structure chart shows who calls whom.
After this lesson
You should be able to
- Decompose a problem statement into sub-problems that each fit in one function.
- Draw a structure chart showing which function calls which.
- Explain why a function should do one thing.
One hard problem, several easy ones
Take: draw a stick figure. As one problem it is vague. Split it and it becomes draw a circle, draw a triangle, draw crossed lines — each of which you can picture immediately. Top-down design is that split, repeated until every piece is obvious.
Stop splitting when a piece is small enough that you could write it without further thought. That is the level where it becomes a function.
The structure chart
A structure chart is a tree. main sits at the top; every function it calls hangs below it; every function those call hangs below them. It shows dependency, not order — a chart tells you who relies on whom, while the code tells you what runs first.
If one function appears under five different parents, that is a signal, not a problem — it is genuinely reusable. If one function has fifteen children, that is a problem: it is doing the work of a whole program.
main
|
+-- draw_circle
+-- draw_intersect
+-- draw_base
|
+-- draw_triangle
|
+-- draw_intersect
+-- draw_baseOne function, one job
A function that computes an average should not also print it. Keep computing separate from printing and you can reuse the computation in a program that writes to a file instead of the screen — and you can test it without reading output by eye.
A useful test: describe the function in one sentence. If your sentence needs the word and, the function probably wants to be two functions.
Try it yourself
A program must read five students' marks, compute the average, find the highest, and print a report. List the functions you would write and draw the structure chart.
Need a hint?
Apply the one-sentence test to each candidate. Reading, computing, and printing are three different sentences.
Check the worked solution
Four functions, each describable without the word and: read_marks fills the array, average_of returns a mean, highest_of returns a maximum, print_report displays. main only orchestrates. Notice average_of and highest_of both take the same array and neither prints — that is what lets you reuse them later for a different report, or test them by checking a returned number instead of reading the screen.
main
|
+-- read_marks(marks, 5)
+-- average_of(marks, 5) -> double
+-- highest_of(marks, 5) -> int
+-- print_report(average, highest)Quick check
Which is the strongest sign that a function should be split in two?
Why this lesson exists
Syllabus mapping
Top-Down Design and Structure Charts · Building Programs from Existing Information
Maps to course outcomes CO1, CO4.