Write pseudocode to process array data
Topic: 10.2 Arrays – Write Pseudocode to Process Array Data
What is an Array? 📚
An array is like a row of lockers in a school hallway. Each locker has a number (the index) and can hold a single item. In programming, an array holds a fixed number of items of the same type, and we access each item using its index.
Indices start at 0, so the first locker is array[0], the second is array[1], and so on up to array[n-1] where n is the total number of lockers.
Key Properties of Arrays 🧩
- Fixed size: once created, the number of elements
ncannot change. - Homogeneous: all elements are of the same data type (e.g., all
int). - Indexed access:
array[i]gives the i‑th element in constant time.
Accessing Elements 🔢
To read or change an element, we use its index:
value = array[3] // read the 4th element array[5] = 42 // write to the 6th element
Pseudocode Example 1: Sum of All Elements ➕
Goal: Calculate the total of all numbers stored in an array arr of length n.
- Set
total = 0. - For
i = 0ton-1do:- Set
total = total + arr[i].
- Set
- Return
total.
In LaTeX: $$\text{total} = \sum_{i=0}^{n-1} \text{arr}[i]$$
Pseudocode Example 2: Find the Largest Element 🏆
- Assume the array is non‑empty. Set
max = arr[0]. - For
i = 1ton-1do:- If
arr[i] > maxthen setmax = arr[i].
- If
- Return
max.
Visualising an Array with a Table 📊
| Index | Value |
|---|---|
| 0 | 12 |
| 1 | 7 |
| 2 | 23 |
| 3 | 5 |
Here, arr[2] = 23 and arr[3] = 5.
Exam Tips for Arrays 🎯
- Read the question carefully: Identify whether you need to search, sort, or compute a value.
- Use clear variable names: e.g.,
index,sum,maxto avoid confusion. - Remember the index range:
0ton-1. Off‑by‑one errors are common. - Show your work: Even if the answer is a single number, write the pseudocode steps.
- Practice with different array sizes: Small arrays (3–5 elements) are easier to trace.
Revision
Log in to practice.
3 views
0 suggestions