Sub topic 4
Arrays and Index Conventions
This chapter assumes you have written basic programs, used arrays or lists in at least one language, and can read the assignment arrow (←) and the FOR, WHILE, and IF keywords from the earlier chapters. The focus here is narrow: how pseudocode names array elements and ranges, and how small choices about where counting starts produce, or prevent, a whole family of bugs.
What an Array Means in Pseudocode
An array is a fixed sequence of values stored in numbered positions. In pseudocode you usually write it as a single capital letter, such as A, and refer to one element with square brackets: A[i] is the element at position i. The number of elements is the array's length, usually written n or length(A).
Pseudocode leaves out the details that real languages force on you. You rarely declare a type, allocate memory, or say whether the array can grow. What you must still say is which index the first element has. Leave that out and your pseudocode is ambiguous, because the same loop header can be correct under one convention and wrong under the other.
1-Based and 0-Based Indexing
There are two common conventions:
| Convention | First element | Last element | Valid indices | Typical users |
|---|---|---|---|---|
| 1-based | `A[1]` | `A[n]` | 1, 2, ..., n | Most algorithm textbooks, MATLAB, Lua, Fortran, R |
| 0-based | `A[0]` | `A[n-1]` | 0, 1, ..., n-1 | C, Java, Python, JavaScript, Go |
Textbook pseudocode favors 1-based indexing because it matches how people count: the third element is A[3]. Most production languages use 0-based indexing because the index then acts as an offset from the start of the array's memory. Neither is more correct. What matters is picking one and sticking to it.
The FindMax function used throughout this tutorial is 1-based:
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 FUNCTIONRead the loop header carefully. FOR i ← 2 TO n includes both endpoints, so i takes the values 2, 3, ..., n. Together with the initial A[1], every position from 1 to n is examined exactly once. If you rewrote this for a 0-based array but kept the same loop header, you would skip A[1], the second element, never mind the first, and read A[n], which does not exist.
Mapping Between the Conventions
The element a person would call "the k-th element" sits at index k under 1-based indexing and at index k - 1 under 0-based indexing. Every conversion follows from this one rule.
Some common expressions translate like this:
| Meaning | 1-based | 0-based |
|---|---|---|
| First element | `A[1]` | `a[0]` |
| Last element | `A[n]` | `a[n-1]` |
| Middle element (lower) | `A[⌊(n+1)/2⌋]` | `a[⌊(n-1)/2⌋]` |
| Every index, in order | `FOR i ← 1 TO n` | `for i in 0 .. n-1` |
| Neighbor after `i` exists when | `i < n` | `i < n - 1` |
| Children of heap node `i` | `2i` and `2i+1` | `2i+1` and `2i+2` |
The heap row matters because some formulas change shape when you convert them, beyond just shifting by 1. A heap's parent and child arithmetic is cleaner under 1-based indexing. That is one reason textbooks keep it.
Ranges: Closed and Half-Open
Pseudocode often refers to part of an array. The usual notation A[i..j] means the closed range: every element from position i through position j, both included. It contains j - i + 1 elements. When j = i - 1 the range is empty, which is a convenient way to describe "nothing processed yet." For example, the insertion sort invariant later in this tutorial says A[1..j-1] is sorted. When j = 2 that range is just A[1].
Many 0-based languages use half-open ranges instead. Python's a[i:j] and range(i, j) include i but exclude j, so they contain j - i elements. The empty range is a[i:i].
| Style | Notation | Includes end? | Element count | Empty when |
|---|---|---|---|---|
| Closed | `A[i..j]` | Yes | `j - i + 1` | `j = i - 1` |
| Half-open | `a[i:j]`, `range(i, j)` | No | `j - i` | `j = i` |
Mixing the two styles is a reliable source of off-by-one errors. Pseudocode's FOR i ← 1 TO n is closed. Python's range(1, n) is half-open and stops at n - 1. A direct copy of the bounds silently drops the last iteration.
Bounds and Out-of-Range Access
A valid index lies within the array's range. Reading A[0] in a 1-based array or a[n] in a 0-based array is an out-of-bounds access. Real languages react in different ways. Python raises IndexError and Java throws ArrayIndexOutOfBoundsException, so the bug gets noticed. C reads whatever memory happens to sit there, so you get garbage or a crash. Python also accepts negative indices such as a[-1] and counts them from the end, so an index that drifts below zero gives a wrong answer with no error at all.
Pseudocode has no runtime to catch these errors, so you catch them yourself. In conditions that guard an access, put the bounds test first and rely on short-circuit AND:
WHILE i ≥ 1 AND A[i] > key DO
i ← i - 1
END WHILEWhen i reaches 0, the first test fails and A[0] is never read. If you reverse the order to A[i] > key AND i ≥ 1, the loop reads A[0] before the bound check runs. State in your conventions that AND short-circuits, so readers know the order is deliberate.
Two-Dimensional Arrays
A two-dimensional array, or matrix, uses two indices: M[r, c] (or M[r][c]) is the element in row r, column c. A matrix with rows rows and cols columns has valid indices 1..rows and 1..cols under 1-based indexing. Write the row index first and say so. Swapping the two indices is a common bug, and it often goes unnoticed on square test matrices because both bounds are equal.
When a matrix is stored as one flat array, the position of M[r, c] in row-major order is:
- 1-based:
(r - 1) × cols + c - 0-based:
r × cols + c
Here is the 0-based formula checked in Python:
rows, cols = 3, 4
flat = list(range(rows * cols)) # values 0..11, row-major
def at(r, c):
return flat[r * cols + c]
print(at(0, 0)) # 0
print(at(1, 2)) # 6
print(at(2, 3)) # 11, the last elementChoosing a Convention
Use these criteria:
- If you are following a textbook algorithm, keep its convention (usually 1-based) so you can compare your work line by line.
- If the pseudocode will be translated immediately into a 0-based language, writing it 0-based removes a conversion step and the bugs that come with it.
- If formulas such as heap children or the midpoint of a range are central to the algorithm, use whichever convention makes them simplest.
- Whatever you choose, do not mix conventions within one document.
The final chapter of this tutorial covers translating a full algorithm. For now, the rule to remember is that converting from 1-based to 0-based means subtracting 1 from every index and checking whether each range bound is inclusive.
Exercise
A 1-based array A has n = 10 elements. How many elements are in A[4..7], and what is the equivalent Python slice of the 0-based list a?
Show answer
A[4..7] is closed, so it holds 7 - 4 + 1 = 4 elements: positions 4, 5, 6, 7. In 0-based terms these are indices 3 through 6. Python slices exclude the end, so the slice is a[3:7], which also holds 7 - 3 = 4 elements.
Exercise
Someone translates "FOR i ← 1 TO n - 1 DO IF A[i] > A[i + 1] THEN ..." to Python as "for i in range(1, n - 1): if a[i] > a[i + 1]: ...". Which comparisons does the Python version miss, and what is the correct loop header?
Show answer
The pseudocode compares every adjacent pair (1,2) through (n-1,n), which is n - 1 comparisons. In 0-based terms those pairs are (0,1) through (n-2,n-1), so i must run from 0 to n-2. The Python version starts at 1, skipping the pair (a[0], a[1]), and its half-open range stops at n-2, which happens to be correct. The fix is "for i in range(0, n - 1):" or simply "for i in range(n - 1):".
Exercise
In a 1-based heap, the children of node i are 2i and 2i + 1. Derive the 0-based formulas and check them for the root.
Show answer
Let j = i - 1 be the 0-based index, so i = j + 1. The 1-based children 2i and 2i + 1 become 2(j + 1) = 2j + 2 and 2j + 3 in 1-based terms. Subtracting 1 to convert back to 0-based gives 2j + 1 and 2j + 2. Check: the root is j = 0, and its children are 1 and 2, the second and third elements, which matches the 1-based children 2 and 3.