Paper 2: Pseudocode step by step (arrays, functions, procedures)

Paper 2: Pseudocode step by step (arrays, functions, procedures)

Arrays 1: boxes, indexes and the FOR loop

1D arrays AS Level 16 min read

On this page
  1. What you need to be able to do
  2. What an array is
  3. Declaring an array
  4. Using one element
  5. Visiting every element: the FOR loop
  6. Dry-running array code
  7. Worked example: a week of rainfall
  8. Practice: three levels
  9. Mistakes that lose marks
  10. Can I do this?

What you need to be able to do

Syllabus 10.2 Arrays (Paper 2)
  • 10.2Explain what an array is and why we use one instead of many separate variables.
  • 10.2Use the terms index, element, lower bound and upper bound.
  • 10.2Declare a 1D array, read and write one element, and process every element with a FOR loop.
  • 10.2Fill (initialise) an array and dry-run code that uses one.

You need: FOR loops. This page goes slowly on purpose: everything else about arrays is built on it.

What an array is

Suppose a program needs the test scores of 5 students. With separate variables you would need Score1, Score2, Score3, Score4, Score5 - and five lines of code for everything you do with them. With 500 students that is impossible.

An array is one name for a whole row of boxes. Every box holds a value of the same data type, and each box has a number, its index, that says which box you mean.

index12345
Score7245886091
The array Score: 5 elements, index 1 to 5.
WordMeaningIn the picture
elementone box of the arraythe box holding 88
indexthe number of a box (its position)3 is the index of the box holding 88
lower boundthe first index1
upper boundthe last index5
Score[3]the value stored in box 388
The most important idea on this page: Score[3] has two parts. The 3 is the index (WHICH box). Score[3] as a whole is the value in that box (WHAT is in it). Mixing them up is the most common array mistake.
In the picture, what is Score[5]? And what is the index of the box holding 45? Score[5] = 91. The value 45 is at index 2.

Declaring an array

DECLARE name : ARRAY[lower:upper] OF type
DECLARE Score : ARRAY[1:5] OF INTEGERDECLARE Names : ARRAY[1:30] OF STRINGDECLARE Seat  : ARRAY[0:75] OF BOOLEAN       // lower bound 0: 76 elements

The number of elements is upper bound - lower bound + 1. So ARRAY[1:30] has 30 elements and ARRAY[0:75] has 76. Most exam arrays start at 1; when one starts at 0 the question says so, and your loops must start at 0 too.

The square brackets hold the bounds, with a colon: ARRAY[1:30]. Writing ARRAY[30] or ARRAY(1 TO 30) loses the declaration mark. The exam often gives a mark for the declaration on its own: “Write pseudocode to declare the Membership array”.

Using one element

An element is used exactly like an ordinary variable. The index goes in square brackets.

Reading and writing single elements
Score[1] ← 72                  // put 72 into box 1Score[2] ← Score[1] - 27       // box 2 gets 72 - 27 = 45OUTPUT Score[2]                 // outputs 45i ← 4Score[i] ← 60                  // the index can be a variable: box 4Score[i + 1] ← 91              // or an expression: box 5

The index being a variable is what makes arrays powerful: change i, and the same line of code works on a different box.

An index outside the bounds - Score[6] or Score[0] for ARRAY[1:5] - is a run-time error: the box doesn't exist. (Our checker stops on it: “index 6 is outside the array bounds 1:5”.)

Visiting every element: the FOR loop

To do something to every element, loop the index from the lower bound to the upper bound. Inside the loop, Score[i] is “the box we are looking at now”.

Output every element
FOR i ← 1 TO 5   OUTPUT Score[i]NEXT i
index12345
Score7245886091
When i = 3, Score[i] means Score[3], the value 88.

Three jobs you will write again and again, all with the same loop:

Initialise, input, calculate
// 1. initialise: set every element to a starting valueFOR i ← 1 TO 5   Score[i] ← 0NEXT i // 2. fill from inputFOR i ← 1 TO 5   OUTPUT "Enter score ", i   INPUT Score[i]NEXT i // 3. fill with a calculated valueFOR i ← 1 TO 5   Score[i] ← i * 10           // 10, 20, 30, 40, 50NEXT i
The exam says “set all elements of the array to FALSE” for Done : ARRAY[1:50] OF BOOLEAN. What do you write? FOR i ← 1 TO 50 · Done[i] ← FALSE · NEXT i
Use the loop variable as the index. FOR i ← 1 TO 5 then Score[5] ← 0 sets box 5 five times and leaves the others untouched.

Dry-running array code

A trace table has a column for each variable, and a column for each array element (or for the element being changed). Go through the code one line at a time and write a value down only when it changes. Here is a real one.

Each element is 3 times the one before it
DECLARE A : ARRAY[1:4] OF INTEGERDECLARE i : INTEGERA[1] ← 2FOR i ← 2 TO 4   A[i] ← A[i - 1] * 3NEXT i
Trace table (generated by actually running the code)
iA[1]A[2]A[3]A[4]
226
318
454

Read it row by row: when i = 2, A[i - 1] is A[1] = 2, so A[2] becomes 6. When i = 3, A[i - 1] is A[2] = 6, so A[3] = 18. The index i - 1 always points at the box just before the current one.

Worked example: a week of rainfall

Example 1 · Rainfall (own example) ★ Easy
Q1Practice6 marks

Write pseudocode to:

  • declare an array Rain to hold the rainfall (whole mm) for 7 days
  • input the 7 values into the array
  • output the total rainfall for the week
  • output the 7 values in reverse order (day 7 first).
1 Read it with me what is actually happening?

Seven numbers come in and are kept in seven boxes. Then we go over the boxes twice: once to add them up, once backwards to print them.

  • declare an arrayDECLARE Rain : ARRAY[1:7] OF INTEGER
  • input the 7 valuesa FOR loop with INPUT Rain[Day]
  • in reverse ordera FOR loop counting down: STEP -1
2 What is it asking for? the target, part by part
  • 1the declarationbounds 1:7, type INTEGER
  • 2the totala running total over every element
  • 3the values backwardsindex from 7 down to 1
3 What do we know? everything the question gives us
  • 7days: the upper bound
  • whole mmINTEGER
  • Each job is a separate loop over the same array: we can only print backwards once all 7 values have been input.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • Findtotal and reverse list
    • Work out firstfill the array: FOR Day ← 1 TO 7, INPUT Rain[Day]
    • Key ideaTotal ← Total + Rain[Day] for every Day
    • Key ideaFOR Day ← 7 TO 1 STEP -1
      • TrapTotal ← 0 before its loop
Why can't we output in reverse while inputting?

When day 1 is input, day 7 hasn't been typed yet: storing them in the array first is what makes the reverse possible.

Does the loop variable have to be called i?

No - Day reads better here. Any INTEGER variable works as an index.

5 Now solve it have a go on paper first, then open the worked solution
  1. Declare the array and an INTEGER for the index and the total.
  2. Loop 1 to 7 and INPUT into Rain[Day].
  3. Set Total to 0, loop 1 to 7 adding Rain[Day], output Total.
  4. Loop 7 down to 1 and output Rain[Day].
Model answer
DECLARE Rain : ARRAY[1:7] OF INTEGERDECLARE Day, Total : INTEGERFOR Day ← 1 TO 7   OUTPUT "Rainfall for day ", Day   INPUT Rain[Day]NEXT DayTotal ← 0FOR Day ← 1 TO 7   Total ← Total + Rain[Day]NEXT DayOUTPUT "Total ", TotalFOR Day ← 7 TO 1 STEP -1   OUTPUT Rain[Day]NEXT Day
6 Check it does the answer make sense?

Run with the values 1 to 7: total 28, then 7, 6, 5, 4, 3, 2, 1 - which is what our checker produced.

Practice: three levels

L1 Basic

Declare, fill, output - one loop at a time.

L1.1 Declare and fill

Declare an array Days that holds the 7 day names, and assign "Monday" … "Sunday" to its elements.

Show the model answer
DECLARE Days : ARRAY[1:7] OF STRINGDays[1] ← "Monday"Days[2] ← "Tuesday"Days[3] ← "Wednesday"Days[4] ← "Thursday"Days[5] ← "Friday"Days[6] ← "Saturday"Days[7] ← "Sunday"

Now the CASE statement from the toolkit page becomes one line: OUTPUT Days[DayNumber].

L1.2 Set all to zero

The array Count : ARRAY[1:26] OF INTEGER has been declared. Write the code to set every element to 0.

Show the model answer
FOR i ← 1 TO 26   Count[i] ← 0NEXT i

L1.3 Input and output

Declare an array for 5 names, input the 5 names, then output them all on separate lines.

Show the model answer
DECLARE Names : ARRAY[1:5] OF STRINGDECLARE i : INTEGERFOR i ← 1 TO 5   INPUT Names[i]NEXT iFOR i ← 1 TO 5   OUTPUT Names[i]NEXT i

L1.4 Dry run

Complete the trace table for this code.

DECLARE N : ARRAY[1:4] OF INTEGERDECLARE i : INTEGERFOR i ← 1 TO 4   N[i] ← i * iNEXT i
iN[1]N[2]N[3]N[4]
Show the completed trace table
iN[1]N[2]N[3]N[4]
11
24
39
416

Each element gets the square of its own index.

L2 Medium

Calculate with the elements; other bounds.

L2.1 Times table

Declare an array Table of 12 integers and fill it so that Table[k] holds 7 × k. Then output the element at index 9.

Show the model answer
DECLARE Table : ARRAY[1:12] OF INTEGERDECLARE k : INTEGERFOR k ← 1 TO 12   Table[k] ← 7 * kNEXT kOUTPUT Table[9]

L2.2 Double them

An array Price : ARRAY[1:6] OF INTEGER already holds 6 prices. Write code to double every price in the array, then output the new prices.

Show the model answer
FOR i ← 1 TO 6   Price[i] ← Price[i] * 2NEXT iFOR i ← 1 TO 6   OUTPUT Price[i]NEXT i

The element is on both sides of ←: read the old value, write the new one back into the same box.

L2.3 Dry run with i - 1

The array X holds 5, 1, 4, 2 (X[1] to X[4]). Complete the trace table.

FOR i ← 2 TO 4   X[i] ← X[i] + X[i - 1]NEXT i
iX[1]X[2]X[3]X[4]
Show the completed trace table
iX[1]X[2]X[3]X[4]
25142
3610
412

Each element becomes the running total so far: 5, 6, 10, 12. X[i - 1] has already been changed when it is used.

L2.4 Zero-based

Hour : ARRAY[0:23] OF INTEGER holds the number of visitors in each hour of a day. Write code to set all elements to 0, then input the number of visitors for hours 9 to 17 only.

Show the model answer
FOR i ← 0 TO 23   Hour[i] ← 0NEXT iFOR i ← 9 TO 17   INPUT Hour[i]NEXT i

The loop bounds come from the question, not always 1 to the size: 0 to 23 for the whole array, 9 to 17 for part of it.

L3 Hard

Indexes that are expressions (i - 1, i + 1, 9 - i).

L3.1 Fibonacci

Declare an array Fib of 15 integers. Set Fib[1] and Fib[2] to 1; every later element is the sum of the two before it (1, 1, 2, 3, 5, 8, …). Fill the array and output Fib[15].

Hint

Which is the first index that can be worked out from the two before it?

Show the model answer
DECLARE Fib : ARRAY[1:15] OF INTEGERDECLARE i : INTEGERFib[1] ← 1Fib[2] ← 1FOR i ← 3 TO 15   Fib[i] ← Fib[i - 1] + Fib[i - 2]NEXT iOUTPUT Fib[15]

The loop starts at 3 because i - 2 must not go below the lower bound.

L3.2 Rotate left

Q : ARRAY[1:5] OF CHAR holds 'A', 'B', 'C', 'D', 'E'. Write code that moves every element one place to the left, and puts the first element at the end: 'B', 'C', 'D', 'E', 'A'.

Hint

What is lost if you start copying without saving Q[1] first?

Show the model answer
DECLARE First : CHARFirst ← Q[1]FOR i ← 1 TO 4   Q[i] ← Q[i + 1]NEXT iQ[5] ← First

Save Q[1] before it is overwritten. The loop stops at 4 (the upper bound - 1) because it reads Q[i + 1]. Shifting elements is pattern 7 on the Arrays 4 page.

L3.3 Copy in reverse

An array A : ARRAY[1:8] OF INTEGER is full. Declare a second array B of the same size and copy A into B in reverse order, so B[1] = A[8] and B[8] = A[1].

Hint

Write the pairs of indexes: 1 with 8, 2 with 7 … What do they always add up to?

Show the model answer
DECLARE B : ARRAY[1:8] OF INTEGERFOR i ← 1 TO 8   B[i] ← A[9 - i]NEXT i

Index i in B matches index 9 - i in A (1 ↔ 8, 2 ↔ 7, …). In general: upper + lower - i.

Mistakes that lose marks

MistakeWrite this instead
Declaring with the size only: ARRAY[20] OF INTEGERARRAY[1:20] OF INTEGER
Using the loop variable but a fixed index: Total ← Total + Score[1]Total ← Total + Score[i]
Outputting i when the question wants the valueOUTPUT Score[i] (the value) - OUTPUT i is the index
Loop bounds that don't match the declaration (0 TO 20 for [1:20])Use exactly the lower and upper bound
Reading A[i + 1] in a loop that goes all the way to the upper boundStop one earlier: TO Upper - 1

Can I do this?

Anything unticked: revise that section first. All ticked: take the quiz.

The multiple-choice and guided questions need JavaScript. The concept checks and exam practice below work without it.

Concept checks

Answer each one in your head first, then open it.

1What is the difference between i and A[i]?Show answer

i is the index, the number of the box. A[i] is the value stored in box number i.

2Why do we often need two separate loops over the same array?Show answer

The first loop fills the array; only when it is full can the second loop use all the values (total, reverse, …).

3What happens if the index goes past the upper bound?Show answer

A run-time error: the program tries to use a box that doesn't exist.

Your progress on this note is saved when JavaScript is on.

⬇️ Download this chapter as a PDF: Full notes · Worksheets · Answers