Video lecture
Watch on YouTube(opens in a new tab)Sub topic 7
Describing Algorithms with Pseudocode
This chapter assumes you can read simple Python, know what loops, conditionals and functions do, and are comfortable with the remainder operator (mod, written % in Python). It also assumes you have seen Euclid's algorithm written as numbered plain-language steps, and that you know the three building blocks of sequence, selection and iteration.
Pseudocode is a way of writing an algorithm that looks like code but is meant for people, not compilers. It keeps the structure of a program, with its loops, branches and assignments, and drops the details a particular language requires, such as type declarations, imports and punctuation rules. The goal is a description precise enough that any competent programmer could turn it into working code in any language, with no guessing about what a step means.
Why Not Just Use Plain Language or Real Code?
Plain-language steps are easy to read, but they get vague once an algorithm has nested loops or several variables. "Go back to step 1" works for four steps. With forty steps it becomes hard to follow. Real code is fully precise, but it ties the description to one language and fills the page with incidental detail. Pseudocode sits between the two.
| Notation | Precision | Language-neutral | Best for |
|---|---|---|---|
| Plain-language steps | Low to medium | Yes | First explanation, non-programmers |
| Pseudocode | High | Yes | Textbooks, design docs, interviews, proofs |
| Program code | Exact | No | Running and testing |
The Running Example
Here is Euclid's algorithm in conventional pseudocode:
function GCD(a, b)
// Precondition: a >= 0, b >= 0, not both zero
// Postcondition: returns gcd(a, b)
while b != 0 do
r <- a mod b
a <- b
b <- r
end while
return a
end functionEach convention in this block exists for a reason. The sections below explain them one at a time.
Core Conventions
No single pseudocode standard exists. Textbooks differ in small ways. Most of them agree on the conventions below, and whichever style you pick, use it the same way throughout a document.
Assignment
Assignment is written with a left arrow: r <- a mod b means "compute a mod b and store it in r." Some authors write := or ←. The arrow keeps assignment separate from equality. In mathematics, a = b is a claim that two things are equal. In pseudocode, a <- b is an action that changes a. Using = for both is the source of a whole family of misreadings.
Comparison and Arithmetic
Comparisons use =, != (or ≠), <, <=, >, >=. Use mod for remainder and div for integer division, because % and // mean different things in different languages. If an operator could be read more than one way, define it once. For example, state whether mod of a negative number can be negative.
Blocks and Indentation
Indentation shows which statements belong to a loop or branch. Many styles also add explicit closers such as end while, end if and end function. The closers are redundant when indentation is clean, but they protect the meaning when text is reflowed, copied into an email or split across a page break.
Control Structures
The three building blocks have standard forms:
// Selection
if x > best then
best <- x
else if x = best then
count <- count + 1
else
skip
end if
// Iteration with an unknown number of passes
while b != 0 do
...
end while
// Iteration over a known range
for i <- 1 to n do
...
end for
// Iteration over a collection
for each x in items do
...
end forUse while when the number of passes depends on the data, and for when the range is known before the loop starts. A reader can then see at a glance which loops need a termination argument.
Functions, Parameters and Return
A function header names the inputs: function GCD(a, b). The statement return a ends the function immediately and hands back a value. If a procedure changes its input rather than returning something, say so in a comment, for example // sorts A in place.
Specification as Comments
The precondition and postcondition belong at the top of the function as comments. They connect the pseudocode to the problem specification. They tell the reader what the algorithm may assume and what it promises. Later chapters on correctness check the body against these two lines.
Collections and Indexing
State whether arrays start at 0 or 1. Many algorithm textbooks use A[1..n]. Python uses items[0] through items[n-1]. Both are fine, but leaving the choice unstated causes off-by-one errors when someone translates your pseudocode. A common notation is length(A) or |A| for the number of elements.
From Pseudocode to Program
Once the pseudocode is precise, translating it is close to mechanical:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6The Python version drops r, because Python's tuple assignment evaluates the whole right side before it assigns anything. That is a language feature. The pseudocode uses an explicit temporary variable so that it does not depend on any language having simultaneous assignment.
Linear search shows how a for each loop with an early return translates:
function LINEAR-SEARCH(items, target)
// Precondition: items is a list (0-indexed); target is any value
// Postcondition: returns the smallest i with items[i] = target, or -1 if none
for i <- 0 to length(items) - 1 do
if items[i] = target then
return i
end if
end for
return -1
end functiondef linear_search(items, target):
for i, x in enumerate(items):
if x == target:
return i
return -1
print(linear_search([4, 8, 15, 16], 15)) # 2
print(linear_search([4, 8, 15, 16], 23)) # -1The postcondition says "smallest i", and the early return is what guarantees it. Writing the postcondition precisely shows which line of the body is responsible for which promise.
Common Errors
Order of Assignment
The most frequent bug in hand-written Euclid pseudocode is this:
// WRONG
while b != 0 do
a <- b
b <- a mod b
end whileAfter a <- b, the old value of a is gone, so b <- a mod b computes b mod b, which is always 0. The loop then stops after one pass and returns the original b. Pseudocode statements run in sequence, one after another, and the temporary r is what keeps the old values available. You can check this in Python:
def gcd_wrong(a, b):
while b != 0:
a = b
b = a % b
return a
print(gcd_wrong(48, 18)) # 18, not 6Hidden Work in One Line
A line such as sort the list or find the maximum of A looks like one step, but it hides a whole algorithm. That is acceptable when the sub-task is standard and its cost is understood. It becomes a problem when you later count steps and treat that line as costing 1. If a line hides a loop, either expand it or name the sub-algorithm, for example best <- MAX(A) // O(n).
Language Leakage
Writing items.append(x), x++ or len(items) ties pseudocode to one language. A reader who does not know that language may misread it. Prefer neutral phrasing: append x to items, x <- x + 1, length(items).
Vague Steps
A step like adjust the values appropriately is not pseudocode. Each line must be definite, so that two readers would carry it out the same way. If you cannot write a line as a concrete operation, you have not finished designing that part of the algorithm.
Missing Boundary Handling
Pseudocode often skips empty inputs, zero and duplicates. Either handle them in the body or exclude them in the precondition. For example, xs is non-empty in a find-maximum function makes best <- xs[0] safe.
A Style Checklist
- Every variable is assigned before it is read.
- Assignment uses
<-. Comparison uses=. - Every block is closed, either by consistent indentation or by an
endkeyword. - Inputs, outputs, preconditions and postconditions appear at the top.
- Array indexing (0-based or 1-based) is stated.
- No line hides a loop without saying so.
- No language-specific syntax or library calls.
Exercises
Exercise
Rewrite the following plain-language algorithm as pseudocode with a header, precondition, postcondition and explicit block closers. "Given a list of numbers, add up the ones that are even and report the total."
Show answer
function SUM-EVENS(xs) // Precondition: xs is a list of integers (possibly empty) // Postcondition: returns the sum of all elements x of xs with x mod 2 = 0 total <- 0 for each x in xs do if x mod 2 = 0 then total <- total + x end if end for return total end function An empty list returns 0, which matches the postcondition because the sum of no numbers is 0.
Exercise
A colleague writes the loop body of Euclid's algorithm as "b <- a mod b; a <- b". What does it return for GCD(48, 18), and why?
Show answer
It returns 18, which is wrong. The first assignment sets b to 48 mod 18 = 12. Then a <- b copies that new value, so a = 12 and b = 12. On the next pass b <- 12 mod 12 = 0 and a <- 0, so the loop ends and the function returns 0... except that the original b was lost in the first step. More precisely: pass 1 gives (a, b) = (12, 12), pass 2 gives (0, 0), and the function returns 0. Either way the answer is wrong, because the old value of b needed for "a <- b" was overwritten before it was used. A temporary variable r fixes this: r <- a mod b, a <- b, b <- r.
Exercise
Identify three problems in this pseudocode and fix them: "function F(A) / for i = 1 to len(A) / if A[i] > m: m = A[i] / return m"
Show answer
First, m is read before it is assigned. Add a precondition that A is non-empty and initialise m <- A[1]. Second, "=" is used for assignment, and the loop range uses the Python call len(A). Use "<-" and length(A), and state that A is 1-indexed. Third, the blocks have no closers and the colon is Python syntax, so the extent of the if and the for is unclear. A fixed version: function F(A) // Precondition: A[1..n] non-empty // Postcondition: returns the largest element; m <- A[1]; for i <- 2 to length(A) do; if A[i] > m then; m <- A[i]; end if; end for; return m; end function.