Write pseudocode for 1D and 2D arrays

Published by Patrick Mutisya · 14 days ago

Cambridge A-Level CS 9618 – Arrays

Topic: 10.2 Arrays

Objective

Write pseudocode for 1‑D and 2‑D arrays.

Key Concepts

  • Arrays are contiguous blocks of memory that store elements of the same type.
  • Indexing starts at 0 in most programming languages.
  • 1‑D arrays are linear; 2‑D arrays can be visualised as a table of rows and columns.
  • Accessing an element: array[i] for 1‑D, array[row][col] for 2‑D.
  • Iterating over arrays uses loops that run from the first index to the last.

Pseudocode – 1‑D Array

  1. Declaration and Initialization

    DECLARE scores[5] AS INTEGER

    FOR i FROM 0 TO 4

    scores[i] ← 0

    END FOR

  2. Assigning \cdot alues

    scores[0] ← 85

    scores[1] ← 92

    scores[2] ← 78

    scores[3] ← 90

    scores[4] ← 88

  3. Accessing an Element

    PRINT "Score at index 2: ", scores[2]

  4. Iterating to Compute Sum

    sum ← 0

    FOR i FROM 0 TO 4

    sum ← sum + scores[i]

    END FOR

    PRINT "Total score: ", sum

Pseudocode – 2‑D Array

  1. Declaration and Initialization

    DECLARE matrix[3][4] AS INTEGER

    FOR row FROM 0 TO 2

    FOR col FROM 0 TO 3

    matrix[row][col] ← 0

    END FOR

    END FOR

  2. Assigning \cdot alues

    matrix[0][0] ← 1 matrix[0][1] ← 2 matrix[0][2] ← 3 matrix[0][3] ← 4

    matrix[1][0] ← 5 matrix[1][1] ← 6 matrix[1][2] ← 7 matrix[1][3] ← 8

    matrix[2][0] ← 9 matrix[2][1] ← 10 matrix[2][2] ← 11 matrix[2][3] ← 12

  3. Accessing an Element

    PRINT "Element at (1,2): ", matrix[1][2]

  4. Iterating to Compute Row Averages

    FOR row FROM 0 TO 2

    sum ← 0

    FOR col FROM 0 TO 3

    sum ← sum + matrix[row][col]

    END FOR

    average ← sum / 4

    PRINT "Average of row ", row, ": ", average

    END FOR

Visualising a 2‑D Array

Row / Col0123
01234
15678
29101112

Suggested diagram: A 3×4 two‑dimensional array with indices (row, column).

Mathematical Notation

For a 1‑D array of length \$n\$, the element at index \$i\$ is denoted \$A[i]\$, where \$0 \le i < n\$.

For a 2‑D array with \$r\$ rows and \$c\$ columns, the element at row \$i\$ and column \$j\$ is denoted \$M[i][j]\$, where \$0 \le i < r\$ and \$0 \le j < c\$.

Common Pitfalls

  • Off‑by‑one errors: remember that the last valid index is length - 1.
  • Assuming 1‑based indexing; always check the language specification.
  • Mixing row and column order when accessing 2‑D arrays.

Practice Questions

  1. Write pseudocode to find the maximum value in a 1‑D array of size 10.
  2. Write pseudocode to transpose a 3×3 matrix.
  3. Given a 2‑D array, write pseudocode to calculate the sum of all elements.