1-D arrays
DECLARE an array
- An array stores many values under one name.
DECLARE Score : ARRAY[1:5] OF INTEGERmakes room for 5 integers.- The numbers
1:5are the first and last index.
DECLARE Score : ARRAY[1:5] OF INTEGER
Score[1] ← 40
OUTPUT Score[1] // → 40
The declaration sets the index bounds
- In
Score : ARRAY[1:5], the first item isScore[1]and the last isScore[5]. Cambridge usually uses a lower bound of 1, but other bounds are valid. ARRAY[0:2]instead has three cells, indexed 0, 1 and 2. Follow the declaration rather than assuming every pseudocode array starts at 1. Python and JavaScript lists/arrays start at 0.
DECLARE Name : ARRAY[1:3] OF STRING
Name[1] ← "Ada"
Name[2] ← "Sam"
OUTPUT Name[2] // → Sam
Loop through an array
- A
FORloop visits each index in turn.
DECLARE Score : ARRAY[1:3] OF INTEGER
Score[1] ← 10
Score[2] ← 20
Score[3] ← 30
DECLARE I : INTEGER
FOR I ← 1 TO 3
OUTPUT Score[I] // 10, 20, 30
NEXT I
Watch out
- The index must stay inside the declared range:
Score[6]is out of[1:5]. ARRAY[1:5]has 5 cells, numbered 1 to 5 — not 0 to 4.
Common mistakes
- Declare an array with its bounds:
DECLARE Values : ARRAY[1:N] OF INTEGER. - Index only within the declared range.
Now you try
- Declare an array, fill it, then read or loop over it.
- Press Check answer to test it.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Declare an array Values of 3 integers. Store 10, 20, 30 in positions 1, 2, 3, then output Values[2] (the answer is 20).
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
The array Values holds 5, 8, 2. Use a FOR loop to add them and output the total (it is 15).
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
The array Values holds 3, 9, 2, 7. Find the largest value and output it (it is 9).
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
The declared array has indices 0 to 2. Fix the loop bounds so the program outputs all three values, in order: 8, 0, 5. Keep the declaration and values.
Click Run to see the output here.