Sub topic 1
Why Write Pseudocode?
Prerequisites
This chapter assumes you can already program in at least one language. You should be comfortable with variables, conditionals, loops, arrays or lists with indexing, and functions that take parameters and return values.
What Pseudocode Is For
Pseudocode describes an algorithm in structured, language-neutral steps. It leaves out syntax details such as semicolons, type declarations, and library calls, so you and your reader can focus on the logic. Use it when you are designing an algorithm, explaining one to someone who uses a different language, or checking an idea on paper before you commit to code. Use real code instead when the details of a particular language or library are the point.
Conventions That Keep It Unambiguous
Pseudocode has no official standard, so pick conventions and apply them consistently:
| Element | Convention | Why |
|---|---|---|
| Assignment | `x ← 5` | Keeps assignment separate from the comparison `=` |
| Keywords | `IF`, `FOR`, `WHILE`, `RETURN` in capitals | Makes control flow stand out from names |
| Blocks | Indentation plus `END IF`, `END FOR` | Shows clearly where each block ends |
| Comparison | `=`, `≠`, `<`, `≤` | Reads like ordinary mathematics |
Sequence, Selection, and Iteration
Every algorithm is built from three structures. In a sequence, statements run in order. In selection, IF … THEN … ELSE picks one branch. In iteration, FOR repeats a counted number of times and WHILE repeats as long as a condition holds.
Arrays and Index Conventions
Many textbooks use 1-based indexing, where A[1] is the first element and A[n] is the last. Python, C, and Java use 0-based indexing instead. State which convention you use, because mixing the two up is a common cause of off-by-one errors.
Procedures, Parameters, and Return Values
A FUNCTION takes parameters and returns a value. A PROCEDURE performs actions and returns nothing. The function below is written in 1-based pseudocode:
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 FUNCTIONFindMax uses all three structures. The first assignment is sequence, the FOR loop is iteration, and the IF is selection. It also declares its inputs, A and n, and its output, max.
Exercise
Rewrite the FOR line of FindMax for a 0-based array of length n.
Show answer
FOR i ← 1 TO n - 1 DO, with max initialized to A[0].