Select a suitable data structure (1D or 2D array) to use for a given task
📚 10.2 Arrays – Choosing the Right Structure
What is an Array?
An array is a collection of items stored in contiguous memory locations. Think of it as a row of lockers, each holding a single item. The items are accessed by an index (starting at 0).
Arrays can be:
- 1‑D (one‑dimensional) – a single row of items.
- 2‑D (two‑dimensional) – a grid of rows and columns, like a spreadsheet.
Analogy: The Library 📚
Imagine a library:
- 1‑D array is a single shelf of books. You pick a book by its position on that shelf.
- 2‑D array is the whole library with rows of shelves. You locate a book by row and column.
When to Use a 1‑D Array
- Data is a simple list (e.g., student grades, daily temperatures).
- Only one dimension of variation is needed.
- Memory is limited – a single row is smaller than a grid.
Example: Storing the scores of 10 students in a single test.
| Student | Score |
|---|---|
| Alice | 88 |
When to Use a 2‑D Array
- Data has two independent dimensions (e.g., rows of students and columns of subjects).
- Operations involve both dimensions (e.g., calculating row totals and column averages).
- You need to represent a matrix or grid (e.g., a chessboard, seating chart).
Example: A timetable where each cell holds a class for a specific day and period.
| Period/Day | Mon | Tue | Wed |
|---|---|---|---|
| 1 | Math | English | Science |
Decision Tree: Pick the Right Array
- Does the problem involve one list of items? → Use 1‑D.
- Are there two independent categories (e.g., rows and columns)? → Use 2‑D.
- Do you need to perform matrix operations (multiplication, transposition)? → 2‑D.
- Is memory a concern and you only need a single dimension? → 1‑D.
Exam Tips 📌
- Read the question carefully: look for keywords like “grid”, “matrix”, or “single list”.
- Sketch a quick diagram: a row of boxes for 1‑D, a grid for 2‑D.
- Remember that array indices start at 0 in most programming languages.
- When in doubt, ask: “How many independent ways can I access the data?”
Quick Test 🚀
Choose the appropriate array type for each scenario:
- Storing the names of 30 students in a class.
- Representing a 5×5 tic‑tac‑toe board.
- Keeping track of the temperature for each hour of a 24‑hour day.
- Recording the scores of 12 students across 4 subjects.
Answers: 1) 1‑D, 2) 2‑D, 3) 1‑D, 4) 2‑D.
Revision
Log in to practice.
2 views
0 suggestions