A

10.2 Arrays

Understanding arrays as data structures, working with one-dimensional and two-dimensional arrays, and implementing algorithms using arrays.

Learning Objectives

By the end of this lesson, you will be able to:

  • Define what an array is and identify its key characteristics
  • Declare and use one-dimensional (1D) arrays in pseudocode
  • Declare and use two-dimensional (2D) arrays in pseudocode
  • Read from and write to array elements using loops
  • Explain the advantages of using arrays over separate variables
  • Apply array concepts to solve real-world problems
  • Trace through array algorithms and predict their output

Key Terms

Array

A data structure containing several elements of the same data type that can be accessed using the same identifier name.

Element

An individual data item stored in an array.

Index (Subscript)

A value used to identify the position of an element in an array.

Lower Bound

The index of the first element in an array (usually 0 or 1).

Upper Bound

The index of the last element in an array.

One-Dimensional Array (1D)

An array with a single dimension, often called a list.

Two-Dimensional Array (2D)

An array with two dimensions, often called a table with rows and columns.

Identifier

The name used to refer to an array.

Data Type

The type of data stored in an array (e.g., INTEGER, STRING).

Nested Loop

A loop inside another loop, commonly used with 2D arrays.

Pseudocode

A simplified programming language used to describe algorithms.

Declaration

The process of defining an array's name, size, and data type.

Array Fundamentals

An array is a data structure containing several elements of the same data type. These elements can be accessed using the same identifier name. The position of each element in an array is identified using the array's index (subscript).

Key Characteristics of Arrays

  • Fixed size: The number of elements is determined when the array is declared
  • Same data type: All elements must be of the same type (e.g., all integers or all strings)
  • Indexed access: Elements are accessed using an index (subscript)
  • Contiguous memory: Elements are stored in consecutive memory locations
  • Lower and upper bounds: The index range is defined by lower and upper bounds

Array Indexing

The index of the first element in an array is called the lower bound, and the index of the last element is the upper bound. The lower bound is usually set as zero or one.

Example: 1D Array with 9 elements

Square brackets are used to indicate array indices: mylist[7] ← 16

Array Visualization

Visualize how a 1D array stores data. Each element has an index and a value. Change the values to see how the array updates.

1D Array: mylist[0:8]

How it works: This 9-element array has indices from 0 to 8 (lower bound = 0, upper bound = 8). Each box shows an element with its index above and value inside.

Real-Life Example: Student Test Scores

Imagine you need to store test scores for a class of 30 students. Instead of creating 30 separate variables (score1, score2, score3...), you can use a single array:

DECLARE testScores : ARRAY [1:30] OF INTEGER
// Now you can access any student's score using testScores[studentNumber]
testScores[1] ← 85 // First student's score
testScores[2] ← 92 // Second student's score
testScores[30] ← 78 // Thirtieth student's score

This is much more efficient than managing 30 separate variables, especially when you need to process all scores (e.g., calculate average).

Check Your Understanding: Array Basics

Answer
  • [1 mark] A data structure containing several elements of the same data type
  • [1 mark] These elements can be accessed using the same identifier name
  • [Additional] Elements are accessed using an index (subscript) that identifies their position
Answer
  • [1 mark] Lower bound: The index of the first element in an array
  • [1 mark] Upper bound: The index of the last element in an array
  • [Additional] The lower bound is usually set as zero or one, defining the starting index
Answer
  • [1 mark] To identify the position of each element in an array
  • [1 mark] To access specific elements using the array name followed by the index in square brackets
  • [Additional] Example: mylist[7] accesses the 8th element if lower bound is 0, or 7th if lower bound is 1
Answer
  • [1 mark] To ensure consistent memory allocation for each element
  • [1 mark] To allow predictable operations on array elements (e.g., arithmetic operations on integers)
  • [Additional] Different data types require different amounts of memory, making array operations complex if mixed
Answer
  • [1 mark] DECLARE prices : ARRAY [1:15] OF REAL
  • [1 mark] OR DECLARE prices : ARRAY [0:14] OF REAL (if using zero-based indexing)
  • [Additional] The data type REAL is used for decimal numbers in pseudocode

One-Dimensional (1D) Arrays

A one-dimensional (1D) array can be referred to as a list that can have many rows but single column. When a 1D array is declared in pseudocode, the lower bound (LB), upper bound (UB) and data type are included.

Declaration and Initialization

Array Declaration

DECLARE mylist : ARRAY [0:8] OF INTEGER

This declares an array named "mylist" with 9 elements (indices 0 to 8), all of type INTEGER.

Accessing Elements

Declared array can then be used as follows:

mylist[7] ← 16

This assigns the value 16 to the element at index 7 (8th element if counting from 0).

Working with Arrays and Loops

A FOR...TO...NEXT loop uses a fixed number of repeats so it is ideal to use with an array, when the number of elements is known, as the loop counter can be used as array index.

Example: Reading Values
INTEGER marks[6] ← {40, 25, 52, 36, 44, 57}
FOR count ← 0 to 5
PRINT marks[count]
NEXT count

This prints all 6 elements of the marks array.

Reading and Writing Data

Writing Data to an Array

Example 1: Inputting Values

Data: 25, 34, 98, 7, 41, 19, 5

FOR Index ← 0 TO 6
INPUT MyList[Index]
NEXT Index
Example 2: Interactive Input
FOR count ← 0 to 5
PRINT "Enter Marks"
INPUT marks[count]
NEXT count

Resulting Array

After executing Example 1 with the given data, the array would contain:

Index MyList
[0]25
[1]34
[2]98
[3]7
[4]41
[5]19
[6]5
Note:

The loop counter (Index) starts at the lower bound (0) and goes to the upper bound (6), allowing access to each array element in sequence.

1D Array Operations Simulator

Practice reading from and writing to a 1D array. The pseudocode on the left shows an algorithm, and the visualization on the right shows how the array changes as the algorithm executes.

Pseudocode Algorithm
DECLARE numbers : ARRAY [0:6] OF INTEGER
// Initialize with zeros
FOR i ← 0 TO 6
numbers[i] ← 0
NEXT i
// Assign values
numbers[0] ← 10
numbers[3] ← 25
numbers[6] ← 42
// Double every element
FOR i ← 0 TO 6
numbers[i] ← numbers[i] * 2
NEXT i
Array: numbers[0:6]
Step 0: Array declared

How it works: This simulation shows how an array changes as an algorithm executes. Click "Next Step" to see each operation applied to the array.

Activity 1: 1D Array Operations

Given the following pseudocode:

DECLARE scores : ARRAY [1:5] OF INTEGER
scores ← {85, 92, 78, 90, 88}
total ← 0
FOR i ← 1 TO 5
total ← total + scores[i]
NEXT i
average ← total / 5
  1. What is the lower bound and upper bound of the array?
  2. What value is stored in scores[3]?
  3. What is the final value of 'total' after the loop completes?
  4. What is the final value of 'average'?
  5. Write pseudocode to find and print the highest score in the array.
Solution:
  1. Lower bound and upper bound:
    Lower bound = 1, Upper bound = 5
  2. scores[3]:
    scores[3] = 78 (index 3 in 1-based indexing is the third element)
  3. Final value of 'total':
    total = 85 + 92 + 78 + 90 + 88 = 433
  4. Final value of 'average':
    average = 433 / 5 = 86.6
  5. Pseudocode to find highest score:
    highest ← scores[1]
    FOR i ← 2 TO 5
    IF scores[i] > highest THEN
    highest ← scores[i]
    ENDIF
    NEXT i
    PRINT "Highest score: ", highest

Check Your Understanding: 1D Arrays

Answer
  • [1 mark] A FOR loop uses a fixed number of repeats which matches the fixed size of an array
  • [1 mark] The loop counter can be used as the array index to access each element in sequence
  • [Additional] Example: FOR i ← 0 TO 5 allows access to array[0], array[1], ..., array[5]
Answer
  • [1 mark] Declares an array called "names"
  • [1 mark] The array has 20 elements with indices from 1 to 20
  • [1 mark] All elements are of data type STRING (text values)
  • [Additional] Lower bound = 1, Upper bound = 20, Size = 20 elements
Answer
DECLARE temperatures : ARRAY [1:8] OF REAL
total ← 0.0
FOR i ← 1 TO 8
OUTPUT "Enter temperature ", i
INPUT temperatures[i]
total ← total + temperatures[i]
NEXT i
average ← total / 8
OUTPUT "Average temperature: ", average

Key points: Array declaration, loop for input, accumulation of total, calculation of average.

Answer
  • [3 marks] Output: 10, 6, 16, 2, 12 (each on a new line or separated by spaces)
  • [Explanation] Each element of the array is doubled: 5×2=10, 3×2=6, 8×2=16, 1×2=2, 6×2=12
Answer
  • [1 mark] Both arrays have 10 elements, but they use different indexing systems
  • [1 mark] The first uses zero-based indexing (indices 0-9), the second uses one-based indexing (indices 1-10)
  • [Additional] The choice affects how elements are accessed: arr[0] vs arr[1] for the first element

Two-Dimensional (2D) Arrays

A 2D array can be referred to as a table, with rows and columns. When a 2D array is declared in pseudocode, the lower bound for rows (LBR) and upper bound for rows (UBR), lower bound for columns (LBC) and upper bound for columns (UBC), and data type are included.

Declaration and Structure

2D Array Declaration

DECLARE NewArray : ARRAY [0:8, 0:2] OF INTEGER

This declares a 2D array with 9 rows (0-8) and 3 columns (0-2), for a total of 27 elements.

Accessing Elements

To initialize a single element in a 2D array:

NewArray[7, 0] ← 16

This assigns the value 16 to the element at row 7, column 0.

Example 2D Array Structure

A table with 9 rows and 3 columns (27 elements) and lower bounds of zero:

Row index [r,0] [r,1] [r,2]
[0,c]273117
[1,c]196748
[2,c]369829
[3,c]422295
[4,c]163561
[5,c]894647
[6,c]217128
[7,c]162313
[8,c]551177

Row indices: 0-8 (lower bound row to upper bound row)
Column indices: 0-2 (lower bound column to upper bound column)

Working with 2D Arrays and Nested Loops

Initializing a 2D Array

Write algorithm using pseudocode to set each element of array ThisTable to zero:

DECLARE ThisTable : ARRAY [0:4, 0:2] OF INTEGER
FOR Row ← 0 TO 4
FOR Column ← 0 TO 2
ThisTable[Row, Column] ← 0
NEXT Column
NEXT Row

This uses nested FOR loops to access every element in the 2D array (5 rows × 3 columns = 15 elements).

Output Contents of a 2D Array

FOR Row ← 0 TO 4
FOR Column ← 0 TO 2
OUTPUT ThisTable[Row, Column] // stay on same line
NEXT Column
OUTPUT Newline // move to next line for next row
NEXT Row

This outputs the array in a table format, with each row on a separate line.

Expected Output Format
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0

2D Array Visualization

Visualize a 2D array as a table with rows and columns. Each cell shows its [row, column] index and value.

2D Array: ThisTable[0:4, 0:2] - 5 rows × 3 columns

How it works: This 5×3 array has row indices 0-4 and column indices 0-2. Each cell shows [row,column] and its value. The top row shows column indices, and the left column shows row indices.

Advantages of Using Arrays Instead of Separate Variables

  • Easier to implement algorithms for searching and organizing data. Values may be accessed via a loop-controlled variable used as index of an array.
  • Makes algorithm easier to design, amend, code, test and understand. Using a single array with indexing is more systematic than many individual variables.
  • Fewer identifiers needed so less storage required. Instead of 40 variable names for 40 students, you use one array name.
Example:

For 40 students: Without arrays = 40 variables (Name1, Name2, ..., Name40). With arrays = 1 array (Name[1:40]).

Real-Life Example: School Timetable

A school timetable can be represented as a 2D array:

DECLARE timetable : ARRAY [1:5, 1:8] OF STRING
// 5 days (Mon-Fri) × 8 periods per day
timetable[1,1] ← "Math" // Monday, Period 1
timetable[1,2] ← "English" // Monday, Period 2
timetable[2,1] ← "Science" // Tuesday, Period 1
timetable[5,8] ← "PE" // Friday, Period 8

This makes it easy to find what subject is taught on any given day and period using timetable[day, period].

Activity 2: 2D Array Operations

A firm records the number of completed amplifiers made by 3 workers over 4 days in a 2D array:

Day\Worker Worker 1 Worker 2 Worker 3
Day 110209
Day 2111611
Day 3102413
Day 4142017

The array is declared as:

DECLARE ProductionData : ARRAY [1:4, 1:3] OF INTEGER
  1. What is the value of ProductionData[3, 2]?
  2. What does ProductionData[2,1] + ProductionData[2,2] + ProductionData[2,3] represent?
  3. Write pseudocode to calculate the total production for each worker over all 4 days.
  4. Write pseudocode to calculate the average daily production for each worker and flag workers with average less than 2 amplifiers per day for investigation.
Solution:
  1. ProductionData[3, 2]:
    Row 3, Column 2 = 24 (Worker 2 on Day 3)
  2. ProductionData[2,1] + ProductionData[2,2] + ProductionData[2,3]:
    Represents the total number of amplifiers produced by all three workers on Day 2.
    Calculation: 11 + 16 + 11 = 38 amplifiers
  3. Pseudocode for total per worker:
    DECLARE WorkerTotal : ARRAY [1:3] OF INTEGER
    FOR WorkerNum ← 1 TO 3
    WorkerTotal[WorkerNum] ← 0
    FOR DayNum ← 1 TO 4
    WorkerTotal[WorkerNum] ← WorkerTotal[WorkerNum] + ProductionData[DayNum, WorkerNum]
    NEXT DayNum
    NEXT WorkerNum
  4. Pseudocode for average and investigation:
    FOR WorkerNum ← 1 TO 3
    WorkerAverage ← WorkerTotal[WorkerNum] / 4
    IF WorkerAverage < 2 THEN
    OUTPUT "Investigate Worker ", WorkerNum
    ENDIF
    NEXT WorkerNum

Check Your Understanding: 2D Arrays

Answer
  • [1 mark] A 2D array is a table-like structure with rows and columns
  • [1 mark] A 1D array is a list with a single dimension, while a 2D array has two dimensions
  • [1 mark] 2D arrays require two indices to access elements: [row, column] vs [index] for 1D arrays
  • [Additional] Example: Student marks for multiple subjects (2D) vs marks for one subject (1D)
Answer
  • [1 mark] DECLARE scores : ARRAY [1:30, 1:5] OF INTEGER
  • [1 mark] OR DECLARE scores : ARRAY [0:29, 0:4] OF INTEGER (zero-based indexing)
  • [Additional] First dimension = students (30), second dimension = subjects (5)
Answer
  • [1 mark] To systematically access every element in the 2D structure
  • [1 mark] The outer loop typically controls rows, and the inner loop controls columns
  • [Additional] Example: FOR row ← 1 TO 5 (outer), FOR col ← 1 TO 3 (inner) accesses 5×3=15 elements
Answer
highest ← scores[1, 1]
FOR row ← 1 TO 4
FOR col ← 1 TO 3
IF scores[row, col] > highest THEN
highest ← scores[row, col]
ENDIF
NEXT col
NEXT row
OUTPUT "Highest value: ", highest

Key points: Initialize with first element, nested loops to check all elements, update when finding higher value.

Answer
  • [1 mark] Easier to implement algorithms for searching and organizing data
  • [1 mark] Makes algorithms easier to design, amend, code, test and understand
  • [1 mark] Fewer identifiers needed so less storage required
  • [Additional] Values can be accessed via a loop-controlled variable used as array index

Key Takeaways

  • An array is a data structure containing several elements of the same data type accessed using a single identifier
  • Array elements are accessed using an index (subscript) that identifies their position
  • The lower bound is the index of the first element; the upper bound is the index of the last element
  • One-dimensional (1D) arrays are lists with a single dimension, declared as ARRAY [LB:UB] OF type
  • Two-dimensional (2D) arrays are tables with rows and columns, declared as ARRAY [LBR:UBR, LBC:UBC] OF type
  • FOR loops are ideal for array processing because the loop counter can be used as the array index
  • Nested loops are used with 2D arrays to systematically access all elements (rows × columns)
  • Arrays make algorithms easier to design, implement, and understand compared to using separate variables
  • Arrays require fewer identifiers and less storage than multiple individual variables
  • Arrays enable efficient implementation of algorithms for searching, sorting, and organizing data
  • In pseudocode, arrays are declared using the DECLARE keyword with bounds and data type specified
  • Array elements are accessed using square brackets: arrayName[index] for 1D, arrayName[row, column] for 2D
  • Real-world applications of arrays include: student marks, timetables, game boards, image pixels, and spreadsheet data

Question Bank

Answer
Question Answer
The number of dimensions of ThisArray 1 (one-dimensional array)
The technical terms for minimum and maximum values that variable n may take Lower bound, upper bound
The technical term for the variable n in the pseudocode expression Index / Subscript
Answer

(a) Efficient pseudocode using array:

DECLARE Name : ARRAY [1:40] OF STRING
DECLARE Index : INTEGER
FOR Index ← 1 TO 40
OUTPUT "Input the name for student ", Index
INPUT Name[Index]
NEXT Index

(b) One advantage:

  • Program code easier to read / modify / debug
  • OR: Easier to access individual elements
  • OR: Single identifier used instead of 40 separate variables
Answer

(a) Two features of an array:

  • Set of data items have a common name
  • Items are referenced using a subscript/index
  • All data items are of the same data type

(b) ProductionData[3, 2]:

24 (Worker 2 on Day 3)

(c) ProductionData[2,1] + ProductionData[2,2] + ProductionData[2,3]:

  • The total number of amplifiers produced by workers 1, 2 and 3 (all three workers)
  • On day 2
Answer
WorkerNum DayNum WorkerTotal[1] WorkerTotal[2] WorkerTotal[3]
111000
122100
133100
144500
2145200
2245360
2345600
2445800
3145809
32458020
33458033
34458050

Final WorkerTotal values: Worker 1 = 45, Worker 2 = 80, Worker 3 = 50

Answer
// (a) Declare array
DECLARE sales : ARRAY [1:5, 1:12] OF REAL
DECLARE productTotal : ARRAY [1:5] OF REAL
DECLARE product, month : INTEGER
// (b) Input sales figures
FOR product ← 1 TO 5
FOR month ← 1 TO 12
OUTPUT "Enter sales for product ", product, " month ", month
INPUT sales[product, month]
NEXT month
NEXT product
// (c) Calculate and output totals
FOR product ← 1 TO 5
productTotal[product] ← 0
FOR month ← 1 TO 12
productTotal[product] ← productTotal[product] + sales[product, month]
NEXT month
OUTPUT "Total sales for product ", product, ": ", productTotal[product]
NEXT product
Answer

Problem: The array is declared with indices 1 to 10 (1-based indexing), but the second FOR loop uses indices 0 to 9 (0-based indexing). This causes an "out of bounds" error when trying to access values[0].

Corrected pseudocode:

DECLARE values : ARRAY [1:10] OF INTEGER
FOR i ← 1 TO 10
INPUT values[i]
NEXT i
// Find average
total ← 0
FOR i ← 1 TO 10 // Changed from 0 TO 9 to 1 TO 10
total ← total + values[i]
NEXT i
average ← total / 10

Alternative correction: Change array declaration to DECLARE values : ARRAY [0:9] OF INTEGER and keep the second loop as is.

Answer

The pseudocode outputs elements where row index equals column index (diagonal elements).

  • When row=1, col=1: matrix[1,1] = 1 → OUTPUT 1
  • When row=2, col=2: matrix[2,2] = 5 → OUTPUT 5
  • When row=3, col=3: matrix[3,3] = 9 → OUTPUT 9

Output: 1, 5, 9 (each on a new line or separated)

Answer
Aspect 1D Array 2D Array
Dimensions One dimension (list) Two dimensions (table)
Declaration ARRAY [LB:UB] OF type ARRAY [LBR:UBR, LBC:UBC] OF type
Indexing Single index: array[index] Two indices: array[row, column]
Memory structure Linear sequence of elements Grid/Rectangular structure
Loop usage Single FOR loop Nested FOR loops (row and column)
Example use case Store student marks for one subject Store student marks for multiple subjects
Real-world example Daily temperature readings for a month Chess board (8×8 grid)

Key similarity: Both store multiple elements of the same data type under a single identifier.