Write pseudocode to process array data

10.2 Arrays – Writing Pseudocode to Process Array Data

1. Where Arrays Fit in the Cambridge AS & A‑Level Computer Science Syllabus

  • Data Types & Structures (Syllabus 10): Arrays are the fundamental collection type used to store homogeneous data.
  • Algorithm Design & Problem‑solving (Syllabus 9): Traversal, searching, sorting, insertion and deletion are core algorithmic techniques.
  • Information Representation (Syllabus 1): Arrays often hold binary, hexadecimal or Unicode values; they model memory blocks.
  • Hardware & CPU Fundamentals (Syllabus 3‑4): Array indexing mirrors address calculation in RAM; bit‑wise manipulation of array elements is a common low‑level operation.
  • System Software (Syllabus 5): Compilers and interpreters translate array operations into machine code; operating systems manage the memory that stores arrays.
  • Security, Ethics & Data Integrity (Syllabus 6‑7): Validation of indices and values prevents out‑of‑range errors and protects data privacy.
  • Databases & Data Management (Syllabus 8): Simple record‑based files can be represented as arrays of structures.
  • Software Development Life‑Cycle (Syllabus 12): Designing, testing and documenting array‑based algorithms follows the SDLC stages.
  • Artificial Intelligence (Syllabus 18): Many AI‑related algorithms (e.g., linear regression, neural‑network weight vectors) start with array data.

2. Notation & Indexing

  • Array bounds – Cambridge pseudocode requires explicit lower and upper bounds:

    DECLARE arr : ARRAY[lowerBound..upperBound] OF TYPE

  • Default 1‑based indexing – The first element is at index 1 unless the question states otherwise.
  • Guard against illegal indices (useful for safety checks):

    IF i < lowerBound OR i > upperBound THEN

    OUTPUT "Index out of range!"

    STOP

    END IF

3. Declaring & Initialising an Array

General declaration syntax:

DECLARE  : ARRAY[lowerBound..upperBound] OF 

Example – an integer array for 10 test scores:

DECLARE scores : ARRAY[1..10] OF INTEGER

All elements receive a default value (0 for numbers, “” for strings, FALSE for booleans).

If a different start value is required, initialise explicitly (see the templates in §5).

4. Accessing & Updating Elements

  • Read: value ← array[i]
  • Write: array[i] ← value
  • In‑place update example (add 5 to each element):

    FOR i ← lowerBound TO upperBound DO

    array[i] ← array[i] + 5

    END FOR

5. Core Array Operations – Pseudocode Templates

OperationPseudocode Template
Initialise all elements to a specific value v
FOR i ← lowerBound TO upperBound DO

array[i] ← v

END FOR

Sum of all elements
SET sum ← 0

FOR i ← lowerBound TO upperBound DO

sum ← sum + array[i]

END FOR

Find maximum value
SET max ← array[lowerBound]

FOR i ← lowerBound+1 TO upperBound DO

IF array[i] > max THEN

SET max ← array[i]

END IF

END FOR

Linear search for a value x
SET found ← FALSE

FOR i ← lowerBound TO upperBound DO

IF array[i] = x THEN

SET found ← TRUE

EXIT FOR

END IF

END FOR

Binary search for a value x (array must be sorted ascending)
SET low ← lowerBound

SET high ← upperBound

SET found ← FALSE

WHILE low ≤ high AND NOT found DO

SET mid ← (low + high) DIV 2

IF array[mid] = x THEN

SET found ← TRUE

ELSEIF array[mid] < x THEN

SET low ← mid + 1

ELSE

SET high ← mid - 1

END IF

END WHILE

Bubble sort (ascending)
FOR pass ← lowerBound TO upperBound-1 DO

FOR i ← lowerBound TO upperBound-pass DO

IF array[i] > array[i+1] THEN

SET temp ← array[i]

SET array[i] ← array[i+1]

SET array[i+1] ← temp

END IF

END FOR

END FOR

Selection sort (ascending)
FOR i ← lowerBound TO upperBound-1 DO

SET minIdx ← i

FOR j ← i+1 TO upperBound DO

IF array[j] < array[minIdx] THEN

SET minIdx ← j

END IF

END FOR

IF minIdx ≠ i THEN

SET temp ← array[i]

SET array[i] ← array[minIdx]

SET array[minIdx] ← temp

END IF

END FOR

Insertion sort (ascending)
FOR i ← lowerBound+1 TO upperBound DO

SET key ← array[i]

SET j ← i-1

WHILE j ≥ lowerBound AND array[j] > key DO

SET array[j+1] ← array[j]

SET j ← j-1

END WHILE

SET array[j+1] ← key

END FOR

Insert value v at position p (right‑shift)
FOR i ← upperBound DOWNTO p+1 DO

array[i] ← array[i-1]

END FOR

SET array[p] ← v

Delete element at position p (left‑shift)
FOR i ← p TO upperBound-1 DO

array[i] ← array[i+1]

END FOR

/* Optional: clear the now‑unused last element */

SET array[upperBound] ← 0

6. Detailed Example – Calculating the Average Grade

Given an array marks[1..n], compute the average and display it to two decimal places.

DECLARE n, i : INTEGER

DECLARE marks : ARRAY[1..100] OF INTEGER

DECLARE total : INTEGER

DECLARE average : REAL

READ n

/* 1️⃣ Input the marks */

FOR i ← 1 TO n DO

READ marks[i]

END FOR

/* 2️⃣ Compute the total */

SET total ← 0

FOR i ← 1 TO n DO

total ← total + marks[i]

END FOR

/* 3️⃣ Calculate and output the average */

SET average ← total / n

OUTPUT "Average = ", average TO 2DP

7. Linking Arrays to Other Syllabus Areas

7.1 Information Representation (Syllabus 1)

  • Binary & Hexadecimal storage: An 8‑bit byte can be modelled as bits[1..8]. Converting a decimal number to binary is a classic array exercise.

    DECLARE n : INTEGER

    DECLARE bits : ARRAY[1..8] OF INTEGER

    SET n ← 173 /* decimal */

    FOR i ← 8 DOWNTO 1 DO

    SET bits[i] ← n MOD 2

    SET n ← n DIV 2

    END FOR

  • Unicode / ASCII strings are arrays of characters; each character can be accessed via its index.
  • BCD (Binary‑Coded Decimal) can be stored as an array of 4‑bit nibbles.

7.2 Multimedia (Syllabus 1.2‑1.3)

  • Images are two‑dimensional arrays of pixel values, e.g. image[1..height][1..width]. A simple greyscale inversion:

    FOR r ← 1 TO height DO

    FOR c ← 1 TO width DO

    SET image[r][c] ← 255 - image[r][c]

    END FOR

    END FOR

  • Sound samples can be stored in a one‑dimensional array of amplitudes.

7.3 Communication & Networks (Syllabus 2)

  • Transmitting an array over a network involves serialising each element. Pseudocode sketch:

    FOR i ← lowerBound TO upperBound DO

    SEND array[i] TO destination

    END FOR

  • Receiving data into an array follows the same pattern with RECEIVE.

7.4 Hardware & CPU Fundamentals (Syllabus 3‑4)

  • Array indexing mirrors address calculation: address = baseAddress + (i‑lowerBound) × elementSize.
  • Bit‑wise operations on integer array elements (AND, OR, XOR, NOT, SHIFT) are essential for low‑level programming and are directly supported by pseudocode:

    SET array[i] ← array[i] AND 0x0F   /* keep lower 4 bits */

7.5 System Software (Syllabus 5)

  • Compilers translate the high‑level array operations shown above into machine instructions that manipulate RAM.
  • Operating systems allocate contiguous memory blocks for static arrays and manage dynamic resizing (not required in Cambridge exams but useful context).

7.6 Security, Privacy & Data Integrity (Syllabus 6‑7)

  • Always validate indices before accessing an array (see the guard in §2).
  • When reading user‑supplied data, check that values fall within expected ranges to avoid overflow or injection attacks.
  • For sensitive data (e.g., passwords) consider clearing the array after use:

    FOR i ← lowerBound TO upperBound DO

    array[i] ← 0

    END FOR

7.7 Databases & Data Management (Syllabus 8)

  • A simple table can be represented as an array of records:

    DECLARE student : RECORD

    id : INTEGER

    name : STRING

    mark : INTEGER

    END RECORD

    DECLARE students : ARRAY[1..30] OF student

  • Searching for a student by ID then becomes a linear search on the students array.

7.8 Software Development Life‑Cycle (Syllabus 12)

  1. Analyse the problem – identify required array size and operations.
  2. Design – choose appropriate templates (traversal, sort, search).
  3. Implement – write clear, indented pseudocode following the Cambridge conventions.
  4. Test – run through edge cases (empty array, single element, maximum capacity, duplicate values).
  5. Maintain – comment any assumptions (e.g., “array is sorted”) and update logical size variables after insert/delete.

7.9 Artificial Intelligence (Syllabus 18)

  • Many introductory AI algorithms start with numeric vectors stored in arrays – e.g., a weight vector for a perceptron:

    DECLARE weights : ARRAY[1..n] OF REAL

    /* initialise */

    FOR i ← 1 TO n DO

    SET weights[i] ← 0.0

    END FOR

  • Training involves traversing the array and updating each element, a pattern identical to the “in‑place update” template.

8. Common Pitfalls & How to Avoid Them

  • Index out of range: Verify loop limits match declared bounds; use the guard from §2 for dynamic indices.
  • Mixing 0‑based and 1‑based indexing: Cambridge pseudocode defaults to 1‑based – only deviate when the question explicitly states a different lower bound.
  • Forgetting to adjust the logical size after insertion or deletion (e.g., increment or decrement n).
  • Not resetting accumulator variables (e.g., sum, total) before re‑using them in a new pass.
  • Applying binary search to an unsorted array: Sort first or revert to linear search.
  • Ignoring data‑type limits: When using bit‑wise operations, remember the size of the underlying type (8‑bit, 16‑bit, etc.).

9. Summary Checklist

  1. Declare the array with correct lowerBound, upperBound and data type.
  2. Confirm the problem’s logical size (e.g., n) fits within the declared bounds.
  3. Initialise the array if a non‑default start value is required.
  4. Use a loop that respects the bounds; add an explicit guard when indices are computed.
  5. Select the appropriate algorithm (initialise, traverse, search, sort, insert, delete) and follow the matching template.
  6. Update the logical size after any insertion or deletion.
  7. Test edge cases: empty array, single element, full capacity, duplicate values, already sorted data.
  8. Document assumptions (sorted?, 1‑based?, maximum size?) and any security checks performed.

10. Practice Questions

  1. Write pseudocode to reverse the elements of an integer array a[1..n] in place.
  2. Given an array temps[1..30] containing daily temperatures, write pseudocode to find the number of days with temperature above the monthly average.
  3. Explain why a binary search requires the array to be sorted and give the pseudocode for binary search on a 1‑based indexed array.
  4. Implement selection sort for an array scores[1..m] and output the sorted list.
  5. Write pseudocode to delete the element at position p from an array data[1..k] and adjust the logical size accordingly.
  6. Convert the decimal number 198 to an 8‑bit binary array bits[1..8] (most‑significant bit first).
  7. Design a simple image‑inversion routine for a greyscale picture stored in image[1..h][1..w].
  8. Show how you would safely transmit an integer array values[1..n] over a network, including a basic error‑check for missing elements.

Suggested diagram: Flowchart illustrating the steps of a linear search through an array (start → initialise index → compare → found? → increment index → end).