Algorithm-to-Program Development · Lesson 1 of 3
From Problem to Algorithm
Turn a problem statement into explicit inputs, outputs, rules and constraints. Decompose responsibilities, choose variables or arrays and design an algorithm before writing code. Resolve what should happen for empty or invalid input.
By the end, you can
- Identify inputs, processes and outputs.
- Decompose a problem into manageable parts.
- Identify suitable data structures.
- Select appropriate algorithms.
Problem analysis
A problem given in English has to be turned into something precise before any code is written, and the way to do that is to answer four questions about it in order.
What are the inputs? List every piece of data that comes from outside — typed by a user, read from a file, measured by a sensor — with its type and the values that are acceptable. What are the outputs? List everything the program must produce, in the form it must appear.
What processing turns one into the other? This is where decomposition does its work: break the requirement into tasks, and each task into steps, until every step is something you could write in one or two lines. Read the marks, validate each one, total them, find the highest, calculate the average, decide the grade, print the report.
What data structures are needed? A single value needs a variable. Many values of the same kind, processed together, need an array — and an array is the answer whenever the requirement says all, each or every. A table of values needs a two-dimensional array, and values that must survive the run need a file.
Only then choose the algorithms: a linear search to find one item, a sort if the output must be ordered, a running total and a count for an average, a flag for a condition discovered inside a loop. Write the whole thing as pseudocode and trace it with a small example before touching a keyboard, because a mistake found here costs a minute and the same mistake found in code costs an hour.
Worth remembering
- Inputs, outputs, processing, data structures — in that order.
- All, each and every in a requirement usually mean an array and a loop.
- Trace the pseudocode with a small example before writing any code.
Worked example
For a class-average program, identify valid mark range, how many marks are read, how totals are accumulated and how the mean is displayed.
Practice
Warm-up · not marked
Check your understanding
Answer in your own words, then compare with the worked answer. Nothing here is saved or scored.
Worked answer
Initialise a total, read and validate five marks, add each accepted mark, divide the total by five, then output the mean.
Check your method, units and explanation against it.
Marked practice
Set 1 of 4 · easiest first · Checked as you go, with the worked answer. Sign in or create a free account to save your progress.