Part 1: Fundamental Concepts of Computing
Part 1: Fundamental Concepts of Computing — read through each chapter in order. Diagrams, tables and worked examples included.
4. Algorithms: Thinking Step by Step
Algorithms: Thinking Step by Step
An algorithm is a clear, finite sequence of steps that solves a problem or completes a task. Long before computers existed, people followed algorithms: a cooking recipe, directions to a friend's house, or the long-division method you learned in school are all algorithms. Programming is largely the skill of designing good algorithms and then expressing them in code.
What Makes a Proper Algorithm
Not every list of instructions qualifies. A well-formed algorithm has five properties:
- Finite — it must eventually stop; it cannot run forever.
- Definite — each step is precise and unambiguous, with exactly one meaning.
- Inputs — it takes zero or more inputs (the information it starts with).
- Outputs — it produces one or more outputs (the result).
- Effective — every step is simple enough to actually be carried out.
"Add a pinch of salt" is fine for a human recipe but is not definite enough for a computer, which needs exact quantities. Learning to think with this level of precision is one of the most valuable habits in programming.
Worked Example: Making Tea
A friendly, everyday algorithm to warm up the idea:
- Fill the kettle with fresh water.
- Switch the kettle on and wait until it boils.
- Place a tea bag in a cup.
- Pour the boiled water into the cup.
- Wait 3 minutes.
- Remove the tea bag.
- Add milk or sugar if desired.
Notice it is finite (ends at step 7), definite (each step is clear), has an input (water, tea bag), and an output (a cup of tea).
Worked Example: Find the Largest of Three Numbers
Here is a computing-style algorithm. We keep a "current biggest" and compare it against each new number. Expressed as pseudocode — informal, language-neutral steps:
INPUT a, b, c
SET largest = a
IF b > largest THEN
SET largest = b
END IF
IF c > largest THEN
SET largest = c
END IF
OUTPUT largest
Trace it with a=4, b=9, c=2: largest starts at 4; b (9) is bigger, so largest becomes 9; c (2) is not bigger, so largest stays 9; output 9. Correct.
A Flowchart for "Largest of Two"
Algorithms with decisions are often drawn as flowcharts, which you will study next. Here is the simplest comparison as a flowchart:
Why Algorithms Matter
For any problem there are usually many possible algorithms, and they are not equally good. One may be faster, another easier to understand, another more reliable. Great programmers spend much of their thinking time on the algorithm before writing code — because a clear plan written in pseudocode or a flowchart turns the actual coding into a straightforward translation job.