Two-Dimensional Arrays, Nested Loops and String Processing

IB Computer Science · Computational Thinking, Problem-Solving and Programming

Two-dimensional arrays. A table of marks — students in rows, tests in columns — is stored as an array of arrays. In IB pseudocode MARKS[R][C] names the element in row R and column C, and both indices start at 0, so a 3 × 4 table has rows 0–2 and columns 0–3. The row index always comes first; MARKS[1][2] is row 1, column 2. The most common exam error is running a loop to 3 instead of 2 and stepping outside the array. Keep the dimensions as named constants (ROWS, COLS) and loop from 0 to ROWS − 1.

Nested loops. Visiting every element needs a loop inside a loop. The outer loop chooses a row, the inner loop walks along it; the inner loop's counter restarts every time the outer loop advances. For 3 rows and 4 columns the inner body runs 3 × 4 = 12 times, and when both dimensions grow to n the work grows as n², which is why nested loops are the usual source of O(n²) algorithms. Which loop is outside determines what you can accumulate: rows outside gives a total per student, columns outside gives a total per test. The classic bug is placing TOTAL = 0 before both loops instead of inside the outer loop, so that totals accumulate across every row. Other nested-loop patterns to recognise: finding the largest element and its position (two variables updated together), counting how many elements satisfy a condition, and checking whether every row sums to the same value.

Strings as sequences. A string is a sequence of characters that can be indexed like an array. The operations examiners expect: length; extracting one character; joining (concatenation); comparing two strings, which works character by character using the character codes, so uppercase letters sort before lowercase and "10" sorts before "9"; converting between a character and its code; and searching for a substring. Standard algorithms built from these: counting vowels (a loop and a condition), reversing a string (build a new string from the last character backwards), checking a palindrome (compare position I with position LENGTH − 1 − I until they meet), and validating a password (loop once, set flags for length, digit, uppercase, then decide). Every string algorithm is a loop from 0 to LENGTH − 1 plus a condition, and the trace table has one row per character.

Collections versus arrays. The IB collection has no index: you reset it, then loop with hasNext and getNext until the end. It grows as items are added, which arrays cannot, but you cannot jump to the fifth item directly. Choose an array when position matters or when the size is known; choose a collection when the number of items is unknown and you only ever process them in order.

TWO-DIMENSIONAL ARRAY: ROW FIRST, THEN COLUMN — AND WHICH IS THE OUTER LOOP MARKS[row][column] — 3 students × 4 tests [0] [1] [2] [3] [0] [1] [2] 72 85 64 90 55 61 78 70 93 88 95 82 MARKS[1][2] = 78: row 1 first, column 2 second indices start from 0 · the last row is [2], not [3] TWO NESTED LOOPS Total per STUDENT (by row): loop R from 0 to 2 TOTAL = 0 loop C from 0 to 3 TOTAL = TOTAL + MARKS[R][C] end loop output TOTAL end loop TOTAL = 0 must be INSIDE the outer loop, BEFORE the inner loop — in the wrong place it accumulates across the whole class total per TEST: swap the two loops, C outer R inner 3 × 4 = 12 runs of the inner loop body — two nested loops are O(n²) when both go to n the outer loop runs 3 times · each time the inner loop runs 4 times · the inner loop counter is RESET each time the outer loop repeats trace table for nested loops: column R, column C, column TOTAL, column output — 12 rows, no abbreviating the most common exam error: running to 3 instead of 2, to 4 instead of 3 — going out of array bounds
The figure on the left is a two-dimensional array MARKS with 3 rows for 3 students and 4 columns for 4 tests; indices start from 0 so the last row is [2] and the last column is [3]. The convention to memorize: the row index comes first and the column index second, so MARKS[1][2] is the cell in row 1, column 2 with the value 78, not 61. The box on the right is pseudocode that computes each student's total score using two nested loops: the outer loop goes through each row, the inner loop goes through each column of that row. The red line points out the most common error in this type of problem: the statement TOTAL = 0 must be inside the outer loop and before the inner loop, so each student starts from 0; if it is placed before both loops, the result is a running total for the whole class. To get the total for each test instead of each student, swap the two loops, with the column outside and the row inside. The bottom box gives the numbers for tracing: the outer loop runs 3 times, each time the inner loop runs 4 times, for 12 runs of the inner loop body in total, and the inner loop's counter is reset each time the outer loop repeats. A trace table for nested loops has a column R, a column C, a column TOTAL and a column output with all 12 rows. The most common exam error is letting the loop run to 3 instead of 2 or to 4 instead of 3 and going out of array bounds.

Worked example: Example 1 — writing and tracing an algorithm to find the student with the highest average

MARKS is a 3 × 4 array as in the figure (row 0: 72, 85, 64, 90; row 1: 55, 61, 78, 70; row 2: 93, 88, 95, 82). Write pseudocode to find the row index with the highest total, then trace it.

Solution

Pseudocode.

BEST = -1
BESTTOTAL = -1
loop R from 0 to 2
  TOTAL = 0
  loop C from 0 to 3
    TOTAL = TOTAL + MARKS[R][C]
  end loop
  if TOTAL > BESTTOTAL then
    BESTTOTAL = TOTAL
    BEST = R
  end if
end loop
output BEST

Three design decisions to explain. One, TOTAL = 0 is inside the outer loop so each row starts again. Two, BESTTOTAL is initialized to −1 (smaller than any possible total) so the first row is certain to be accepted; initializing to 0 would also work here because scores are non-negative, but −1 is the safe habit. Three, update BEST and BESTTOTAL together — forgetting one of the two is a classic error.

Trace. R = 0: TOTAL goes 0 → 72 → 157 → 221 → 311; 311 is greater than −1 so BESTTOTAL = 311, BEST = 0. R = 1: TOTAL 0 → 55 → 116 → 194 → 264; 264 is not greater than 311, no change. R = 2: TOTAL 0 → 93 → 181 → 276 → 358; 358 is greater than 311 so BESTTOTAL = 358, BEST = 2. Output 2. The full trace table has 12 rows for the inner loop; in the exam room write it all out, because the marks are in the table, not in the final answer.

A frequently asked variation. The highest total and the highest average give the same row because every row has the same number of columns — a response that notices this saves one division and earns credit for understanding.

Worked example: Example 2 — checking symmetry and counting words in a string

(a) Write an algorithm to check whether a string S is a palindrome (reads the same forwards and backwards), ignoring case. (b) Write an algorithm to count the words in a sentence, where words are separated by exactly one space. State the boundary test cases for each.

Solution

(a) Palindrome.

S = toLower(S)
N = length(S)
I = 0
OK = true
loop while I < N div 2 and OK
  if S[I] ≠ S[N - 1 - I] then OK = false
  I = I + 1
end loop
output OK

Points to explain: you only need to compare up to the middle of the string (N div 2), because the second half mirrors the first; the mirror character of position I is N − 1 − I, not N − I — this is the most common off-by-one error; and exit early when OK is false so there are no pointless iterations. Boundary cases: the empty string (N = 0, no iterations, OK true — you need to decide whether that is the intended meaning), a one-character string, strings of even length such as "abba" and odd length such as "aba", and a string that differs only at the middle characters of an even length.

(b) Word count.

N = length(S)
if N = 0 then output 0
else
  COUNT = 1
  loop I from 0 to N - 1
    if S[I] = " " then COUNT = COUNT + 1
  end loop
  output COUNT
end if

The number of words equals the number of spaces plus one — assuming exactly one space between words and no leading or trailing space. That is precisely the precondition, and the answer must state it. Boundary cases: the empty string (handled separately because the formula gives 1 instead of 0), a single word with no spaces, and cases that violate the precondition such as two adjacent spaces or a trailing space — the algorithm gives a wrong result there, and a good answer states a more robust approach: count only when you meet a non-space character whose previous character is a space or the start of the string.

Common mistake

Trap 1 — setting TOTAL = 0 before both loops. The total will accumulate across all rows; the initialization must be inside the outer loop, before the inner loop.
Trap 2 — going out of array bounds. Indices start from 0, so the last row of 3 rows is 2; the mirror character of I is N − 1 − I.
Trap 3 — updating the maximum value but forgetting the position. BEST and BESTTOTAL must change together in the same if block.

Key takeaway

Lesson 3 wrap-up. Four things to take into the exam room. One, row first, column second, indices from 0, loop up to ROWS − 1. Two, the outer loop decides what you accumulate by, and initialization sits inside the outer loop. Three, a string is an array of characters: every string algorithm is a loop from 0 to LENGTH − 1 plus a condition. Four, an array when you need positions, a collection when the number of elements is unknown.

← Standard Algorithms, Data Structures and Efficiency · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Sub-programs, Pre- and Post-conditions, Testing and Debugging →