Arrays: one-dimensional and two-dimensional
An array stores many values of the same data type under one name, each at its own index. Arrays and loops go together: most array answers are a loop that visits every element.
One-dimensional arrays
The declaration gives the lowest and highest index and the data type. Each element is then used with its index in square brackets. Cambridge pseudocode usually numbers from 1, but questions say if an array starts at 0.
DECLARE Rainfall : ARRAY[1:7] OF INTEGER
DECLARE Day, Total : INTEGER
Total <- 0
FOR Day <- 1 TO 7
OUTPUT "Rainfall on day", Day
INPUT Rainfall[Day]
Total <- Total + Rainfall[Day]
NEXT Day
OUTPUT "Weekly total:", TotalTwo-dimensional arrays
A 2D array is a table with rows and columns, and each element needs two indexes: Sales[Shop, Week]. To visit every element, use a loop inside a loop, one for each index.
DECLARE Sales : ARRAY[1:3, 1:4] OF INTEGER
DECLARE Shop, Week, ShopTotal : INTEGER
FOR Shop <- 1 TO 3
ShopTotal <- 0
FOR Week <- 1 TO 4
Sales[Shop, Week] <- Shop * Week
ShopTotal <- ShopTotal + Sales[Shop, Week]
NEXT Week
OUTPUT "Shop", Shop, "total:", ShopTotal
NEXT ShopParallel arrays
When each item has two pieces of data of different types, such as a name and a score, two arrays can share the same index: Names[3] and Scores[3] belong to the same player.
Where marks go
- Declaring an array without its index range or data type.
- A loop that goes one past the end of the array, such as 0 TO 7 for ARRAY[1:7].
- Putting the two indexes of a 2D array the wrong way round.
- Resetting a total inside the wrong loop, so it only counts the last row.
- Using the array name without an index when one element is meant.
Try a question
3 MARKS · MARKED ON THIS PAGEA farmer records how many eggs her hens lay on each of the 7 days of one week. Write pseudocode that: - declares a one-dimensional array Eggs with index 1 to 7 to store INTEGER values - uses a FOR loop to input the number of eggs for each day, storing each value in the next element of Eggs - adds up all the values stored in Eggs into a variable Total - outputs only the value of Total (for example 45), with no other text. Declare every variable you use.
solutionPseudocode
Loading...
Type your answer first.