1D & 2D Arrays
Arrays are the most fundamental data structure in programming. They store fixed-size collections of elements of the same type in contiguous memory. Understanding arrays is critical for efficient data processing, forming the basis for sorting, searching, and more complex structures like matrices.
Learning Objectives
- 11.5.2.1 Use the terms upper and lower bounds of an array
- 11.5.2.3 Write code using one-dimensional and two-dimensional arrays
Conceptual Anchor
The Locker Row Analogy
Imagine a row of numbered lockers in a school hallway. Each locker has a fixed number (its index), can hold exactly one item (a value), and all lockers are the same size (same data type). You can go directly to locker #5 — you don't need to open lockers #1 through #4 first. This is random access, and it's what makes arrays fast.
A one-dimensional (1D) array is a single row of lockers. A two-dimensional (2D) array is a grid of lockers — like a wall of mailboxes with rows and columns. To find your mailbox, you need two numbers: the row and the column.
Rules & Theory
Key Terminology
| Term | Definition | Example |
|---|---|---|
| Array | An ordered, fixed-size collection of elements of the same data type stored in contiguous memory locations. | int marks[5]; |
| Index | The position number used to access a specific element. In C++ and pseudocode, indexing starts at 0. | marks[0] = first element |
| Lower Bound | The smallest valid index of the array. | For marks[5] → lower bound = 0 |
| Upper Bound | The largest valid index of the array. | For marks[5] → upper bound = 4 |
| Size / Length | The total number of elements. size = upper bound − lower bound + 1 |
For marks[5] → size = 5 |
| Element | A single value stored at a specific index. | marks[2] = 87; |
1D Array — Declaration & Initialization
Pseudocode:
DECLARE marks : ARRAY[0:4] OF INTEGER
marks[0] ← 90
marks[1] ← 78
marks[2] ← 85
marks[3] ← 92
marks[4] ← 88C++:
// Declaration and initialization
int marks[5] = {90, 78, 85, 92, 88};
// Or declare first, then assign
int marks[5];
marks[0] = 90;
marks[1] = 78;
marks[2] = 85;
marks[3] = 92;
marks[4] = 88;Memory Layout
Arrays are stored in contiguous memory. If marks[0] is at memory
address 1000 and each int is 4 bytes, then marks[1] is at 1004,
marks[2] at 1008, etc. The formula is:
address = base + index × sizeof(type).
2D Array — Declaration & Initialization
A 2D array is essentially an array of arrays — a table with rows and columns.
Pseudocode:
DECLARE grid : ARRAY[0:2, 0:3] OF INTEGER
// 3 rows × 4 columns
// Access: grid[row, col]
grid[0, 0] ← 1
grid[0, 1] ← 2
grid[1, 0] ← 5
grid[2, 3] ← 12C++:
// 3 rows, 4 columns
int grid[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access element at row 1, column 2
cout << grid[1][2]; // Output: 7| Aspect | 1D Array | 2D Array |
|---|---|---|
| Indices needed | 1 (position) | 2 (row, column) |
| Real-world analogy | A single row of seats | A cinema seating plan |
| C++ declaration | int a[5]; |
int a[3][4]; |
| Pseudocode | ARRAY[0:4] OF INT |
ARRAY[0:2, 0:3] OF INT |
| Total elements | size | rows × columns |
Worked Examples
1 Traversing a 1D Array — Linear Search
Find whether a value exists in an array.
Pseudocode:
DECLARE names : ARRAY[0:4] OF STRING
names ← ["Alice", "Bob", "Clara", "David", "Eve"]
DECLARE target : STRING
OUTPUT "Enter name to find: "
INPUT target
DECLARE found : BOOLEAN ← FALSE
FOR i ← 0 TO 4
IF names[i] = target THEN
OUTPUT target, " found at index ", i
found ← TRUE
ENDIF
NEXT i
IF found = FALSE THEN
OUTPUT target, " not found"
ENDIFC++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string names[5] = {"Alice", "Bob", "Clara", "David", "Eve"};
string target;
cout << "Enter name to find: ";
cin >> target;
bool found = false;
for (int i = 0; i < 5; i++) {
if (names[i] == target) {
cout << target << " found at index " << i << endl;
found = true;
}
}
if (!found) {
cout << target << " not found" << endl;
}
return 0;
}2 Sum & Average of Array Elements
Calculate the total and average of numeric values stored in a 1D array.
Pseudocode:
DECLARE scores : ARRAY[0:4] OF INTEGER ← [90, 78, 85, 92, 88]
DECLARE total : INTEGER ← 0
FOR i ← 0 TO 4
total ← total + scores[i]
NEXT i
DECLARE average : REAL ← total / 5
OUTPUT "Total: ", total
OUTPUT "Average: ", averageC++:
#include <iostream>
using namespace std;
int main() {
int scores[5] = {90, 78, 85, 92, 88};
int total = 0;
for (int i = 0; i < 5; i++) {
total += scores[i];
}
double average = (double)total / 5;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
return 0;
}3 Finding Maximum in a 1D Array
Pseudocode:
DECLARE temps : ARRAY[0:6] OF REAL ← [23.1, 19.5, 28.3, 22.0, 31.7, 25.4, 20.8]
DECLARE maxVal : REAL ← temps[0]
DECLARE maxIdx : INTEGER ← 0
FOR i ← 1 TO 6
IF temps[i] > maxVal THEN
maxVal ← temps[i]
maxIdx ← i
ENDIF
NEXT i
OUTPUT "Maximum temperature: ", maxVal, " at day ", maxIdx + 1C++:
#include <iostream>
using namespace std;
int main() {
double temps[7] = {23.1, 19.5, 28.3, 22.0, 31.7, 25.4, 20.8};
double maxVal = temps[0];
int maxIdx = 0;
for (int i = 1; i < 7; i++) {
if (temps[i] > maxVal) {
maxVal = temps[i];
maxIdx = i;
}
}
cout << "Maximum temperature: " << maxVal
<< " at day " << maxIdx + 1 << endl;
return 0;
}4 Working with a 2D Array — Classroom Grades
Store grades for 3 students across 4 subjects and find each student's average.
Pseudocode:
// grades[student][subject]
DECLARE grades : ARRAY[0:2, 0:3] OF INTEGER
grades ← [[85, 90, 78, 92],
[70, 88, 95, 80],
[92, 76, 84, 91]]
DECLARE studentNames : ARRAY[0:2] OF STRING ← ["Alice", "Bob", "Clara"]
FOR s ← 0 TO 2
DECLARE total : INTEGER ← 0
FOR subj ← 0 TO 3
total ← total + grades[s, subj]
NEXT subj
DECLARE avg : REAL ← total / 4
OUTPUT studentNames[s], " average: ", avg
NEXT sC++:
#include <iostream>
#include <string>
using namespace std;
int main() {
int grades[3][4] = {
{85, 90, 78, 92},
{70, 88, 95, 80},
{92, 76, 84, 91}
};
string names[3] = {"Alice", "Bob", "Clara"};
for (int s = 0; s < 3; s++) {
int total = 0;
for (int subj = 0; subj < 4; subj++) {
total += grades[s][subj];
}
double avg = (double)total / 4;
cout << names[s] << " average: " << avg << endl;
}
return 0;
}Pitfalls & Common Errors
Off-by-One Error (Fence Post Error)
The most common array mistake. An array of size 5 has indices 0–4, not 1–5.
Accessing arr[5] on a 5-element array causes undefined behaviour in C++ (buffer
overflow).
- Wrong:
for (int i = 0; i <= 5; i++)— iterates 6 times! - Correct:
for (int i = 0; i < 5; i++)— iterates 5 times ✓
Uninitialized Arrays
In C++, local arrays are not automatically initialized to zero. They contain garbage values. Always initialize explicitly:
int arr[5] = {0}; // All elements set to 0
int arr[5] = {}; // Same effect in C++Fixed Size
Arrays in C++ have a fixed size determined at compile time. You cannot resize
them after declaration. If you declare int arr[10];, you always have exactly 10
slots — no more, no less. Plan your size carefully.
2D Array Row/Column Confusion
In grid[row][col], the first index is the row and the
second is the column. Swapping them gives wrong data. Think:
Row comes before Column, just like R comes
before C in the alphabet.
Pro-Tips for Exams
Exam Strategy — Bounds Questions
When asked about bounds, always state: Lower bound = 0, Upper bound =
size − 1. For a 2D array ARRAY[0:R-1, 0:C-1] the total elements = R ×
C. Examiners love asking "how many elements?" — multiply rows by columns.
Exam Strategy — Writing Pseudocode Loops
- For 1D arrays:
FOR i ← 0 TO n-1 - For 2D arrays: Use nested loops. Outer loop = rows, inner loop = columns.
- Always declare the array with its type:
DECLARE arr : ARRAY[0:N-1] OF INTEGER - Use meaningful variable names:
row,colinstead ofi,jto avoid confusion.
Exam Strategy — Trace Table Tips
When tracing array operations in an exam, draw the array as a row of boxes with indices above them. Update values in the boxes as the loop iterates. This visual approach prevents mistakes and earns method marks even if the final answer is wrong.
Graded Tasks
Define the terms: array, index, lower
bound, upper bound. Give the lower and upper bounds of
ARRAY[0:99] OF REAL.
Explain, using a diagram, how elements of a 1D array of 6 integers are stored in memory starting at address 2000. What is the address of the element at index 4 if each integer occupies 4 bytes?
Write a C++ program that reads 10 integers from the user into an array, then outputs them in reverse order.
Write pseudocode that takes a 2D array ARRAY[0:4, 0:2] OF INTEGER representing 5
students' marks in 3 subjects, and finds the student with the highest total.
A programmer writes for (int i = 1; i <= 10; i++) to traverse an array
declared as int data[10];. Identify the two bugs in this loop and explain the
consequences of each.
Design a C++ program that uses a 2D array to store a 5×5 multiplication table. The program should fill the table automatically and display it in a formatted grid.
Self-Check Quiz
ARRAY[0:7] OF STRING?int grid[4][6]; contain?arr[10] on an array
declared as int arr[10];?arr[i]?