Thinking in algorithms
An algorithm is a step-by-step recipe for solving a problem. Before you write a single line of code, the best programmers work out the algorithm, in their head, on paper or in plain English.
A problem-solving process
- Understand the problem. What goes in (input)? What should come out (output)? Try a few examples by hand.
- Break it down into smaller steps.
- Write the steps in plain language (called pseudocode).
- Translate to code, one step at a time.
- Test with normal cases, edge cases (empty, zero, huge) and bad input.
- Improve it: make it clearer, then faster if needed.
Example: find the largest number in a list
1. Understand. Input [4, 17, 9, 2] → output 17.
2–3. Pseudocode:
set "biggest" to the first number
for each number in the list:
if the number is bigger than "biggest":
set "biggest" to that number
answer is "biggest"4. Code (both languages follow the pseudocode line by line):
5. Test edge cases. What about an empty list []? Try it. numbers[0] doesn't exist. A robust version would check for that first. Thinking about edge cases is what separates working code from correct code.
Common building blocks
Almost every algorithm is built from three patterns:
| Pattern | Meaning | Example |
|---|---|---|
| Sequence | Do steps in order | Read the input, then calculate, then print |
| Selection | Choose based on a condition | If the total is over 500, give a discount |
| Iteration | Repeat steps | For each item in the cart, add its price |
Example: is a number prime?
A prime number is divisible only by 1 and itself. Pseudocode:
if n < 2: not prime
for each d from 2 up to the square root of n:
if n divides evenly by d: not prime
otherwise: primeWhy stop at the square root? If n = a × b, one of a or b must be ≤ √n. Checking up to √n is much faster than checking every number below n. That's algorithmic thinking.
Efficiency: same answer, different speed
Two ways to add up the numbers 1 to n:
Programmers describe this with Big-O notation: the loop is O(n) (the work grows with n), and the formula is O(1) (constant work). You'll go deeper in the Data Structures & Algorithms track.
Practice
Write pseudocode first, then code: count how many vowels are in a sentence. Test it with an empty string and with a string in CAPITALS.
1.What is pseudocode?
2.What is an "edge case"?