Write pseudocode for 1D and 2D arrays
10.2 Arrays – A-Level CS 9618
What is an Array?
An array is a collection of elements that are stored in contiguous memory locations. Think of it as a row of lockers where each locker holds a single item. Each item can be accessed directly using its index (starting from 0). Arrays are useful when you need to store many values of the same type and access them quickly.
1‑D Arrays 📦
A one‑dimensional array is a simple list. Example: int scores[5]; creates an array that can hold 5 integers.
Common Operations
- Assign a value:
scores[2] = 88; - Retrieve a value:
int x = scores[2]; - Loop through all elements:
- Initialize index:
int i = 0; - Condition:
i < 5; - Increment:
i++;
- Initialize index:
Pseudocode Example
| Step | Pseudocode |
|---|---|
| 1 | Create array int arr[10] |
| 2 | For i = 0 to 9 do |
| 3 | arr[i] = i * 2 |
| 4 | End For |
2‑D Arrays 📊
A two‑dimensional array can be visualised as a spreadsheet or a chessboard: rows and columns. Example: int matrix[3][4]; creates 3 rows and 4 columns.
Accessing Elements
Use two indices: matrix[row][col]. Remember that indices start at 0, so the first element is matrix[0][0].
Common Operations
- Assign a value:
matrix[1][2] = 5; - Retrieve a value:
int y = matrix[1][2]; - Loop through all rows and columns:
- For
r = 0to2do - For
c = 0to3do -
process(matrix[r][c]) - End For
- End For
- For
Pseudocode Example
| Step | Pseudocode |
|---|---|
| 1 | Create matrix int mat[3][4] |
| 2 | For r = 0 to 2 do |
| 3 | For c = 0 to 3 do |
| 4 | mat[r][c] = r + c |
| 5 | End For |
| 6 | End For |
Analogy: The Locker Room & Spreadsheet
- A 1‑D array is like a single row of lockers: each locker (index) holds one item. You can quickly open locker i to get the item.
- A 2‑D array is like a grid of lockers (rows × columns). To find a specific locker, you say “row r, column c”. This is exactly how a spreadsheet works, making it easy to organise data in tables.
Key Takeaways 🧩
- Arrays store elements of the same type in contiguous memory.
- Indices start at 0; the last index is
size - 1. - 1‑D arrays are simple lists; 2‑D arrays are grids (rows × columns).
- Pseudocode helps plan algorithms before coding in a specific language.
- Use loops to initialise, process, or display array contents efficiently.
Practice Challenge 🤓
Write pseudocode to calculate the sum of all elements in a 2‑D array int data[4][5]. Show the nested loops and the accumulation variable.
Revision
Log in to practice.