Sub topic 2
Conventions That Keep Pseudocode Unambiguous
Pseudocode helps only when every reader runs it the same way in their head. If one reader takes = to mean "store" and another takes it to mean "compare," the two will trace different algorithms from the same text. This chapter sets out a small set of conventions for assignment, operators, keywords, and block structure. The rest of the tutorial uses them.
This chapter assumes you have written basic programs in at least one language, and that you know variables, conditionals, loops, and functions. It covers notation only. Later chapters cover how to use control structures, arrays, and procedures well.
Where Ambiguity Comes From
Most ambiguity in pseudocode comes from habits carried over from real languages. The same symbol means different things in different languages:
| Symbol | C, Java, Python | Pascal, Ada | Mathematics |
|---|---|---|---|
| `=` | assignment | equality test | equality statement |
| `==` | equality test | not used | not used |
| `:=` | not used (Python 3.8 uses it for an assignment expression) | assignment | "is defined as" |
| `/` | integer or real division, depending on language and types | real division | real division |
A reader cannot tell which of these meanings you intend. The fix is to choose symbols that no common language has claimed, or to state your meaning once and then keep to it.
Assignment
Write assignment with a left arrow: x ← x + 1. Read it as "x gets x plus one." The arrow shows direction. The value on the right is computed first and then stored in the variable on the left. Nobody mistakes the arrow for a comparison.
Keep = for equality tests only. With that rule, IF count = 0 THEN has one meaning.
total ← 0
count ← count + 1
average ← total / countEach assignment changes one variable. If you need to exchange two values, write out the temporary variable. Don't write a, b ← b, a unless you have said that the right-hand sides are all evaluated before any variable is stored:
temp ← a
a ← b
b ← tempWhen you trace this by hand, each line becomes one row in a trace table. That makes it easy to check, and it shows why the line b ← a on its own would be wrong.
Operators and Their Exact Meaning
State any operator whose behaviour varies between languages. The four that cause the most trouble are division, remainder, logical operators, and loop bounds.
Arithmetic
Use × or * for multiplication. Use / only for exact (real) division. When you want integer division, write DIV. Write MOD for the remainder. With positive operands these behave the same everywhere: 7 DIV 2 is 3 and 7 MOD 2 is 1. With negative operands, languages disagree:
import math
# Python rounds integer division down, toward negative infinity
print(-7 // 2) # -4
print(-7 % 2) # 1
# C and Java truncate toward zero; math.trunc shows that result
print(math.trunc(-7 / 2)) # -3
print(-7 - 2 * math.trunc(-7 / 2)) # -1If your algorithm can see negative values, say which rule DIV and MOD follow. Otherwise, state that the inputs are non-negative.
Comparison and Logic
Use =, ≠, <, ≤, >, ≥ for comparisons. Write AND, OR, and NOT as words, which are easier to read than &&, ||, and !.
Say whether AND and OR short-circuit. Short-circuit evaluation means the right operand is not evaluated if the left operand already decides the result. A guard such as this depends on it:
WHILE i ≥ 1 AND A[i] > key DO
i ← i - 1
END WHILEWhen i reaches 0, the test A[i] > key would read outside a 1-based array. With short-circuit AND, that read never happens. Make the assumption explicit, for example in a note at the top of your pseudocode: "AND and OR short-circuit, left to right."
Loop Bounds
FOR i ← 1 TO n includes both ends: it runs with i = 1, 2, …, n. Python's range(1, n) excludes n. This one difference causes many off-by-one errors when pseudocode becomes code. In your pseudocode, TO always includes the upper bound. If n is less than the starting value, the loop body runs zero times. For a descending loop, write FOR i ← n DOWNTO 1 and don't rely on the reader guessing the direction.
Keywords
Write keywords in capitals so they stand out from variable names. Close every block with a matching keyword. Use one fixed set of keywords:
| Purpose | Opening | Closing |
|---|---|---|
| Selection | `IF condition THEN`, `ELSE IF`, `ELSE` | `END IF` |
| Counted loop | `FOR i ← a TO b DO` | `END FOR` |
| Pre-test loop | `WHILE condition DO` | `END WHILE` |
| Post-test loop | `REPEAT` | `UNTIL condition` |
| Procedure with no result | `PROCEDURE Name(params)` | `END PROCEDURE` |
| Function with a result | `FUNCTION Name(params)` | `END FUNCTION` |
| Exit with a value | `RETURN expression` | none |
Don't swap in synonyms halfway through, such as LOOP WHILE in one place and WHILE in another, or ENDIF next to END IF. A reader who sees two spellings will wonder whether they mean two things.
Note that REPEAT … UNTIL keeps looping while its condition is false, which is the opposite of WHILE. Since the condition's meaning is reversed, check that loop especially carefully when tracing.
Indentation and Block Structure
Indent the body of every block by a fixed amount, such as four spaces. Closing keywords and indentation do the same job twice, and that redundancy is deliberate. When the two disagree, you have found an error before tracing anything.
Closing keywords also remove the "dangling else" ambiguity. In this version, nothing shows which IF the ELSE belongs to:
IF x > 0 THEN
IF y > 0 THEN
result ← 1
ELSE
result ← 2With indentation and closing keywords, the structure is fixed:
IF x > 0 THEN
IF y > 0 THEN
result ← 1
ELSE
result ← 2
END IF
END IFHere, x = −1 leaves result unchanged. If the ELSE belonged to the outer IF, result would become 2. Different readers would get different answers from the unstructured version.
Names, Comments, and Level of Detail
Choose names that describe roles: largest, count, key. Single letters are fine for loop counters (i, j) and for the conventional array A with length n. Write comments with // and use them to explain intent, not to repeat the line.
You may write a single high-level step, such as swap A[i] and A[j] or sort A, when that step is not what you are trying to explain. Each step must still have exactly one possible meaning. Here is a quick test: could two competent programmers turn the step into code that behaves differently? If so, refine it. find the middle element fails the test for even-length arrays, because there are two middle elements. mid ← (low + high) DIV 2 passes it.
Write a short header for any non-trivial algorithm that gives what it takes in and what it produces:
// Input: array A[1..n] of integers, n ≥ 1
// Output: the largest value in A
// Conventions: arrays are 1-based; AND/OR short-circuit
FUNCTION FindMax(A, n)
max ← A[1]
FOR i ← 2 TO n DO
IF A[i] > max THEN
max ← A[i]
END IF
END FOR
RETURN max
END FUNCTIONThe header states the precondition n ≥ 1. Without it, a reader would have to guess what A[1] means for an empty array.
Common Errors
- Using
=for both assignment and comparison in the same document. - Leaving out closing keywords and relying only on indentation. Indentation is easily lost when text is copied.
- Writing
/when you mean integer division. - Relying on short-circuit evaluation without saying so.
- Mixing inclusive pseudocode bounds with exclusive, language-style bounds.
- Writing high-level steps that have more than one reasonable meaning.
- Changing keyword spelling or style partway through.
Exercise
A classmate writes "IF total = limit THEN total = 0". Rewrite the line using this chapter's conventions and explain what problem the original causes.
Show answer
Write "IF total = limit THEN total ← 0 END IF" with the assignment indented on its own line inside the block. In the original, the same symbol "=" is used for both the test and the store, so a reader cannot be sure whether the second "=" is another comparison. Keeping "=" for tests and "←" for assignment removes the doubt.
Exercise
Under this chapter's conventions, how many times does the body of "FOR k ← 3 TO 7 DO" run, and how many times does the body of "FOR k ← 5 TO 4 DO" run?
Show answer
The first runs 5 times (k = 3, 4, 5, 6, 7) because TO includes both bounds. The second runs 0 times because the starting value is already past the upper bound.
Exercise
What do -9 DIV 4 and -9 MOD 4 evaluate to under Python's rule (round down), and under C's rule (truncate toward zero)?
Show answer
Under Python's rule, -9 DIV 4 = -3 and -9 MOD 4 = 3, since -3 × 4 + 3 = -9. Under C's rule, -9 DIV 4 = -2 and -9 MOD 4 = -1, since -2 × 4 + (-1) = -9. Pseudocode that may see negative values must say which rule it uses.