Sub topic 6
From Problem Statement to Pseudocode with Stepwise Refinement
This chapter assumes you can already write pseudocode with assignment (←), IF, FOR, and WHILE, and that you can define a FUNCTION or PROCEDURE with parameters and a return value. Earlier chapters covered those conventions. This chapter is about a different skill: starting from a problem written in plain English and getting to pseudocode that is detailed enough to trace and translate.
What Stepwise Refinement Is
Stepwise refinement is a way of designing an algorithm from the top down. You start by stating the whole solution as one step. Then you replace that step with a few smaller steps, and you keep replacing steps until every line is something you could write as a single statement or a call to a procedure you have already defined.
Each round of replacement is called a refinement level. Level 0 is the problem restated as one action. The last level is pseudocode you can trace by hand.
Refinement works because it lets you make decisions in order of importance. At the top you decide what the major phases are. Further down you decide how each phase works. You only pick loop bounds and index variables when you get to the bottom level.
A Worked Problem
Here is the problem statement:
"Given the exam scores for a class, print the mean score and the number of students who scored at or above the mean. If there are no scores, print a message saying so."
Level 0: State the Whole Task
ReportScores(S, n)This line names the task and its inputs: an array S of n scores, indexed from 1. Writing the inputs down now forces an early decision about what data the algorithm receives. If you skip this, the inputs tend to get invented halfway through the design.
Level 1: Break It into Phases
PROCEDURE ReportScores(S, n)
1. Handle the case where there are no scores
2. Compute the mean of the scores
3. Count the scores that are at or above the mean
4. Print the mean and the count
END PROCEDUREThese steps are still English, which is fine at this level. What matters is that each step has one job and the steps are in a workable order.
This level already shows a fact that the problem statement left out: step 3 depends on the result of step 2. You can't count the scores above the mean until you know the mean, so the algorithm needs two passes over the data. Finding ordering constraints like this one is a big part of what refinement is for.
Level 2: Refine Each Phase
Refine one step at a time. Leave the other steps as they are while you work.
Step 1 becomes a guard:
IF n = 0 THEN
PRINT "No scores"
RETURN
END IFStep 2 is a sum followed by a division:
total ← 0
FOR i ← 1 TO n DO
total ← total + S[i]
END FOR
mean ← total / nRefining this step raises a question the English version hid: is / integer division or real division? If the scores are 70 and 75, integer division gives 72 and real division gives 72.5, and the count in step 3 can change depending on which one you use. Write the decision down, either as a comment or as a convention note at the top of the algorithm. Here, / means real division.
Step 3 is a counting loop:
count ← 0
FOR i ← 1 TO n DO
IF S[i] ≥ mean THEN
count ← count + 1
END IF
END FORStep 4 is a single line already: PRINT mean, count.
Level 3: Package Phases as Procedures
When a refined step grows into a loop with its own variables, you can move it into its own function. The top-level procedure then reads the same way as Level 1:
// Convention: arrays are 1-based; "/" is real division.
PROCEDURE ReportScores(S, n)
IF n = 0 THEN
PRINT "No scores"
RETURN
END IF
mean ← Mean(S, n)
count ← CountAtLeast(S, n, mean)
PRINT mean, count
END PROCEDURE
FUNCTION Mean(S, n)
total ← 0
FOR i ← 1 TO n DO
total ← total + S[i]
END FOR
RETURN total / n
END FUNCTION
FUNCTION CountAtLeast(S, n, t)
count ← 0
FOR i ← 1 TO n DO
IF S[i] ≥ t THEN
count ← count + 1
END IF
END FOR
RETURN count
END FUNCTIONCountAtLeast takes a threshold t as a parameter instead of reading mean directly. That makes it a general-purpose function that you can trace on its own, with any threshold you choose.
When to Stop Refining
A step is refined enough when a programmer could translate it without making any design decisions. These signs help you judge that:
| Signal | Refined enough? | Example |
|---|---|---|
| The line maps to one statement in most languages | Yes | `count ← count + 1` |
| The line calls a procedure that is already defined | Yes | `mean ← Mean(S, n)` |
| The line contains "find", "process", or "handle" with no detail | No | `Handle bad scores` |
| A reader would need to choose a loop bound or index | No | `Go through the scores` |
| The line depends on a library call specific to one language | Too far | `scores.sort(reverse=True)` |
The last row is a mistake in the opposite direction. Pseudocode that names Python or Java library methods has stopped being language-neutral. Write sort S into descending order and leave the choice of library to whoever translates it.
Common Errors in Refinement
Refining Unevenly
A common pattern is to work one phase down to individual statements while the others are still vague English. This feels productive, but problems in the vague phases, such as a missing ordering dependency, show up late and force you to rewrite. Take every step to the same level before going deeper.
Mixing Levels in One Block
If a block contains both Compute the mean and total ← total + S[i], it mixes two levels of detail, and the reader can't tell what is finished and what isn't. Each block should be all one level. You can fix a mixed block by refining the English lines or by moving the detailed lines into a function.
Losing the Edge Cases from the Statement
The problem statement said "if there are no scores, print a message." That requirement is easy to forget once you are focused on loops. A good habit is to make every explicit condition in the statement its own Level 1 step, as step 1 does here. Without that guard, Mean would divide by zero when n = 0.
Deciding Data Representation Too Late
If you don't decide at Level 0 that scores come in as an array with a known length, you may later write a loop with no clear bound. Inputs, outputs, and index conventions belong at the top level of the design.
Refinement and the Rest of the Process
Refinement produces procedures that are small and have clear inputs. That pays off later in three ways. Small procedures are short enough to trace in a trace table. A procedure that takes its inputs as parameters, as CountAtLeast(S, n, t) does, can be tested on its own with chosen inputs. And each procedure translates into one function in real code.
Exercise
Refine this problem to Level 1 and then Level 2: "Given an array A of n integers, print the second-largest distinct value, or print 'none' if there are fewer than two distinct values." At Level 1, what ordering or edge-case issue should the steps make explicit?
Show answer
One possible Level 1 is: (1) find the largest value, (2) find the largest value that is strictly less than it, tracking whether any such value exists, (3) print that value or "none". Step 2 depends on step 1, so a simple version needs two passes. At Level 2, step 1 is a FindMax loop. Step 2 loops over A with a flag found ← false and a variable second, and updates them when A[i] < max AND (NOT found OR A[i] > second). Step 3 prints second if found is true and "none" otherwise. The edge cases to make explicit are n = 0, n = 1, and an array where every value is the same. In all three, step 2 finds nothing and the output is "none". With n = 0, step 1 also has no first element to start from, so it needs its own guard.
Exercise
A student's Level 2 block reads: "total ← 0 / Process every score / mean ← total / n". What is wrong with it, and how would you fix it?
Show answer
The block mixes levels. "Process every score" is Level 1 English placed between concrete statements, and it doesn't say what processing means or what the loop bounds are. Replace it with FOR i ← 1 TO n DO total ← total + S[i] END FOR, or move the whole computation into a Mean function. The block also needs a guard for n = 0 before the division.
Exercise
Why does CountAtLeast take the threshold t as a parameter instead of computing the mean inside itself?
Show answer
Taking t as a parameter keeps the function to one job, counting values at or above a threshold. It avoids computing the mean twice, and it lets you trace or test the function on its own with any threshold you pick, such as a t equal to one of the scores, to check the ≥ boundary.