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

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

Arrays 5: parallel arrays, copying and arrays in modules

1D arrays AS Level 17 min read

On this page
  1. What you need to be able to do
  2. Pattern 9: parallel arrays
  3. Pattern 10: copy or filter into a second array
  4. Arrays in procedures and functions
  5. Worked example: a class results system
  6. Practice: three levels
  7. Mistakes that lose marks
  8. Can I do this?

What you need to be able to do

Syllabus 10.2 Arrays, 11.3 Structured programming (Paper 2)
  • 10.2Use parallel arrays: the same index in two arrays describes the same thing.
  • 10.2Copy or filter items from one array into another, with a separate index for each array.
  • 11.3Use a global array inside a procedure or function, and pass an array as a parameter (BYVAL or BYREF).

You need: Arrays 4 (swap and bubble sort) and Functions and procedures (parameters, BYREF).

Pattern 9: parallel arrays

An array holds one data type. To store a name and a mark for each student, Paper 2 often uses two arrays side by side: Name[i] and Mark[i] belong to the same student. They are called parallel arrays. The index is the link.

index123456
Name"Ali""Bina""Cyrus""Dua""Eman""Faris"
index123456
Mark648147819255
Index 3 in both arrays: Cyrus scored 47.
9Parallel arrays: find in one, read the other

Work out the INDEX using one array, then use that same index in the other. Pattern 3 already gave you the index of the highest value - here that is exactly what is needed.

Use it when the question says the name of the student with …, each … has a corresponding …, the array … and the array … are used together

Template
Best ← 1FOR i ← 2 TO 6   IF Mark[i] > Mark[Best] THEN      Best ← i   ENDIFNEXT iOUTPUT Name[Best], " scored ", Mark[Best]

Trap Keeping only the highest MARK (Max ← Mark[i]) loses the index, so you can't find the name. Keep the index.

Sorting parallel arrays

If you sort Mark and forget Name, every mark ends up next to the wrong student. Whenever two elements of one array swap, the same two elements of the other array must swap too. That needs a Temp of each data type.

Sort by mark, highest first, keeping the pairs together
FOR i ← 1 TO 5   FOR j ← 1 TO 6 - i      IF Mark[j] < Mark[j + 1] THEN         TempMark ← Mark[j]         Mark[j] ← Mark[j + 1]         Mark[j + 1] ← TempMark         TempName ← Name[j]         Name[j] ← Name[j + 1]         Name[j + 1] ← TempName      ENDIF   NEXT jNEXT i
index123456
Name"Eman""Bina""Dua""Ali""Faris""Cyrus"
index123456
Mark928181645547
After the sort every name is still next to its own mark.
Paper 2 also gives the 2D version of the same idea: Result : ARRAY[1:30, 1:2] OF STRING with the name in column 1 and the mark in column 2 (see the 2D arrays page). And an array of RECORDS is a third way. Read which one the question uses.

Pattern 10: copy or filter into a second array

To copy only some elements into another array (the passes, the names starting with A, the used elements), you need two indexes: i walks through the source array, and k says where the next item goes in the target. k only moves when something is copied, so the target fills from the front with no gaps.

i123456
Mark648147819255
k123456
Passed"Ali""Bina""Dua""Eman""Faris"""
i visits all 6; k only reaches 5, because Cyrus (47) is skipped.
10Filter with two indexes

i goes through every element of the source; k counts what has been copied and is also the position of the last copied item. At the end, k is how many were copied.

Use it when the question says copy … into, store … in a second array, create a new array containing only …, remove the gaps

Template
k ← 0FOR i ← 1 TO 6   IF Mark[i] >= 50 THEN      k ← k + 1      Passed[k] ← Name[i]   ENDIFNEXT iOUTPUT k, " passed"

Trap Using i for the target too (Passed[i] ← Name[i]) copies them into the SAME places - the gaps stay.

See the trace table for pattern 10
iMark[i]k
1641
2812
347
4813
5924
6555

k stays at 2 on the row where i = 3: Cyrus is skipped.

Why does k start at 0 and go up BEFORE the copy, not after? Then k always equals the number copied so far, so it can be output or returned at the end. (Starting at 1 and adding after the copy also works, but then the count is k - 1 - an easy slip.)

Arrays in procedures and functions

Most Paper 2 scenario questions say “a global array … is used”. A global array is declared in the main program, and every module can read and change it directly - it is not passed as a parameter. That is what the earlier pages did.

Sometimes the question says the array is passed as a parameter instead. Then the module gets its own name for it, and the parameter's type is written ARRAY OF INTEGER (no bounds).

An array as a parameter
FUNCTION CountAbove(Values : ARRAY OF INTEGER, Limit : INTEGER) RETURNS INTEGER   DECLARE i, Count : INTEGER   Count ← 0   FOR i ← 1 TO 6      IF Values[i] > Limit THEN         Count ← Count + 1      ENDIF   NEXT i   RETURN CountENDFUNCTION PROCEDURE AddBonus(BYREF Values : ARRAY OF INTEGER, BYVAL Bonus : INTEGER)   DECLARE i : INTEGER   FOR i ← 1 TO 6      Values[i] ← Values[i] + Bonus   NEXT iENDPROCEDURE // main programOUTPUT CountAbove(Mark, 55)CALL AddBonus(Mark, 5)OUTPUT CountAbove(Mark, 55)
The array is …What the module can doHow to write it
globalread and change it directlyuse its name, e.g. Mark[i] - no parameter
passed BYVAL (the default)work on a copy: changes are lost when the module endsValues : ARRAY OF INTEGER
passed BYREFchange the caller's arrayBYREF Values : ARRAY OF INTEGER

Run AddBonus with BYVAL instead of BYREF and the second line outputs 4 again: the bonus was added to a copy and thrown away. So: to change an array that was passed in, pass it BYREF.

BYREF and BYVAL apply to every parameter after them, until the other word appears. In AddBonus(BYREF Values : ARRAY OF INTEGER, Bonus : INTEGER) Bonus would be BYREF too, so a call like CALL AddBonus(Mark, 5) is wrong (5 is not a variable). Write BYVAL Bonus, or put the BYREF parameters last.
Don't pass a global array as a parameter when the question says it is global, and don't re-declare it inside the module (DECLARE Mark : ARRAY[1:6] OF INTEGER inside a procedure makes a new, empty local array that hides the global one).

Worked example: a class results system

A typical last question, cut down: parallel global arrays, a filter into a third array, and a module that uses another module.

ModuleDescription
CountMerit()
  • called with a mark threshold
  • copies the name of every student whose mark is at least the threshold into the global array Merit, from Merit[1] with no gaps
  • sets every remaining element of Merit to an empty string
  • returns the number of names copied
ShowMerit()
  • called with a threshold
  • uses CountMerit()
  • outputs the names in Merit, one per line, then the message “n students”, or “No students” if there are none
Example 1 · CountMerit() and ShowMerit() (own example) ★★★ Hard
Q1Practice9 marks

Global parallel arrays Name : ARRAY[1:30] OF STRING and Mark : ARRAY[1:30] OF INTEGER hold the class. An unused element of Name contains an empty string. A third global array Merit : ARRAY[1:30] OF STRING is used for the results. Write pseudocode for the two modules in the table above.

1 Read it with me what is actually happening?

CountMerit is pattern 10 (filter with two indexes) plus pattern 9 (the mark decides, the name is copied). Then it tidies up the rest of Merit, which may still hold old names. ShowMerit just calls it and prints what it made.

  • copies the name … whose mark is at leasttest Mark[i], copy Name[i] - the same i
  • from Merit[1] with no gapsa second index k for Merit
  • sets every remaining element … to an empty stringa second loop from k + 1 to 30
  • returns the number of names copiedRETURN k
  • uses CountMerit()call it once, keep its answer in a variable
2 What is it asking for? the target, part by part
  • 1CountMerit → INTEGERfilter, tidy, return the count
  • 2ShowMeritcall, then output the list or “No students”
3 What do we know? everything the question gives us
  • 30elements in each array
  • ""an unused Name element
  • An unused student has Name[i] = "" - skip it, whatever its Mark holds.
  • If no names are copied, k = 0 and the tidy-up loop runs from 1 to 30: the whole of Merit is cleared.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • FindCountMerit(Threshold)
    • Work out firstthe filter loop: test Name[i] <> "" AND Mark[i] >= Threshold; k ← k + 1; Merit[k] ← Name[i]
    • Thenclear Merit[k + 1 … 30]
    • Trapcalling CountMerit twice in ShowMerit (once to test, once to loop) - store the result in n
Why clear the rest of Merit?

It may still hold names from an earlier call, and the description says the rest must be empty.

Why does ShowMerit loop to n, not 30?

Only the first n elements were filled this time.

5 Now solve it have a go on paper first, then open the worked solution
  1. CountMerit: k ← 0; FOR i ← 1 TO 30: if Name[i] <> "" AND Mark[i] >= Threshold then k ← k + 1, Merit[k] ← Name[i].
  2. FOR i ← k + 1 TO 30: Merit[i] ← "". RETURN k.
  3. ShowMerit: n ← CountMerit(Threshold); if n = 0 output “No students”, else output Merit[1 … n] then “n students”.
Model answer
FUNCTION CountMerit(Threshold : INTEGER) RETURNS INTEGER   DECLARE i, k : INTEGER   k ← 0   FOR i ← 1 TO 30      IF Name[i] <> "" AND Mark[i] >= Threshold THEN         k ← k + 1         Merit[k] ← Name[i]      ENDIF   NEXT i   FOR i ← k + 1 TO 30      Merit[i] ← ""   NEXT i   RETURN kENDFUNCTION PROCEDURE ShowMerit(Threshold : INTEGER)   DECLARE i, n : INTEGER   n ← CountMerit(Threshold)   IF n = 0 THEN      OUTPUT "No students"   ELSE      FOR i ← 1 TO n         OUTPUT Merit[i]      NEXT i      OUTPUT n, " students"   ENDIFENDPROCEDURE
6 Check it does the answer make sense?

Tested with the six students above: threshold 80 gives Bina, Dua, Eman and “3 students”, and clears the old names; 95 gives “No students”.

Practice: three levels

L1 Basic

Look up, filter to output, plain copy.

L1.1 Look up a mark

Using the parallel arrays Name and Mark (6 students, all used), input a name and output that student's mark, or Not found.

Show the model answer
DECLARE Who : STRINGDECLARE Pos : INTEGERINPUT WhoPos ← 0FOR i ← 1 TO 6   IF Name[i] = Who THEN      Pos ← i   ENDIFNEXT iIF Pos = 0 THEN   OUTPUT "Not found"ELSE   OUTPUT Mark[Pos]ENDIF

Search Name for the index, then read Mark at that index. (Names are unique here, so carrying on after finding it is harmless.)

L1.2 Everyone above 60

Output the name of every student whose mark is above 60.

Show the model answer
FOR i ← 1 TO 6   IF Mark[i] > 60 THEN      OUTPUT Name[i]   ENDIFNEXT i

Test one array, output the other, same i.

L1.3 Copy everything

Copy all 6 elements of Mark into a second array Backup : ARRAY[1:6] OF INTEGER.

Show the model answer
FOR i ← 1 TO 6   Backup[i] ← Mark[i]NEXT i

A plain copy keeps the positions, so one index is enough. You need two indexes only when you leave items out.

L2 Medium

Index of the lowest, filter into a new array, an array parameter.

L2.1 Lowest scorer

Output the name of the student with the lowest mark. If two share it, output the first.

Show the model answer
DECLARE Low : INTEGERLow ← 1FOR i ← 2 TO 6   IF Mark[i] < Mark[Low] THEN      Low ← i   ENDIFNEXT iOUTPUT Name[Low]

Keep the index of the lowest. Using < (not <=) keeps the FIRST of equal marks.

L2.2 Names starting with a letter

Input a letter. Copy every name that starts with it into Found : ARRAY[1:6] OF STRING with no gaps, then output how many were copied.

Show the model answer
DECLARE Letter : CHARINPUT Letterk ← 0FOR i ← 1 TO 6   IF LEFT(Name[i], 1) = Letter THEN      k ← k + 1      Found[k] ← Name[i]   ENDIFNEXT iOUTPUT k

Pattern 10 with a string test (LEFT from the strings page).

L2.3 Average of a parameter

Write a function Average() that takes an array of 6 integers as a parameter and returns their average.

Show the model answer
FUNCTION Average(Values : ARRAY OF INTEGER) RETURNS REAL   DECLARE i, Total : INTEGER   Total ← 0   FOR i ← 1 TO 6      Total ← Total + Values[i]   NEXT i   RETURN Total / 6ENDFUNCTION

The array arrives as a parameter, so the function uses the parameter's name (Values), not Mark. It only reads it: BYVAL is fine.

L3 Hard

Filter in place, sort parallel arrays, two targets.

L3.1 Remove the gaps

Item : ARRAY[1:8] OF STRING has unused elements ("") in random places. Write a procedure Compact() that moves the used items to the front in the same order, with all the "" after them - using only Item itself.

Hint

Could the target of pattern 10 be the same array as the source?

Show the model answer
PROCEDURE Compact()   DECLARE i, k : INTEGER   k ← 0   FOR i ← 1 TO 8      IF Item[i] <> "" THEN         k ← k + 1         Item[k] ← Item[i]      ENDIF   NEXT i   FOR i ← k + 1 TO 8      Item[i] ← ""   NEXT iENDPROCEDURE

Pattern 10 into the SAME array: k is never bigger than i, so an item is only ever copied backwards onto a place already read. Then clear what is left.

L3.2 Alphabetical register

Sort the parallel arrays Name and Mark (6 students) so the names are in alphabetical order, each mark staying with its student.

Show the model answer
DECLARE j, TempMark : INTEGERDECLARE TempName : STRINGFOR i ← 1 TO 5   FOR j ← 1 TO 6 - i      IF Name[j] > Name[j + 1] THEN         TempName ← Name[j]         Name[j] ← Name[j + 1]         Name[j + 1] ← TempName         TempMark ← Mark[j]         Mark[j] ← Mark[j + 1]         Mark[j + 1] ← TempMark      ENDIF   NEXT jNEXT i

The comparison is on Name now, but both arrays still swap together.

L3.3 Split into two

Write a procedure Split() that takes an array of 10 integers BYVAL and two arrays BYREF, Even and Odd (each 10 elements). It copies the even numbers into Even and the odd ones into Odd, with no gaps, and fills the unused elements of both with -1.

Show the model answer
PROCEDURE Split(Values : ARRAY OF INTEGER, BYREF Even : ARRAY OF INTEGER, BYREF Odd : ARRAY OF INTEGER)   DECLARE i, e, o : INTEGER   FOR i ← 1 TO 10      Even[i] ← -1      Odd[i] ← -1   NEXT i   e ← 0   o ← 0   FOR i ← 1 TO 10      IF Values[i] MOD 2 = 0 THEN         e ← e + 1         Even[e] ← Values[i]      ELSE         o ← o + 1         Odd[o] ← Values[i]      ENDIF   NEXT iENDPROCEDURE

Two targets, so two target indexes (e and o) - plus i for the source. Filling with -1 first is simpler than tidying up afterwards.

Mistakes that lose marks

MistakeWrite this instead
Keeping the highest value, then searching again for the nameKeep the index of the highest; read Name[Best]
Sorting one parallel array onlySwap the same two elements in every parallel array
Copying with one index: Target[i] ← Source[i] inside an IFA second index k for the target
Not clearing the rest of the target arrayFill from k + 1 to the end with the unused value
Changing an array passed BYVAL and expecting the caller to see itBYREF, or work on the global array
Re-declaring a global array inside a moduleJust use it - it is already declared

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.

1Why are parallel arrays needed at all?Show answer

One array holds one data type, so a name (STRING) and a mark (INTEGER) need an array each; the shared index joins them.

2Why can pattern 10 copy within the same array safely?Show answer

k never runs ahead of i, so each item is written to a place that has already been read.

3When is a global array better than a parameter, and the other way round?Show answer

Global: the question says so, and many modules share one data set. Parameter: the module must work on different arrays (it is reusable and easier to test).

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

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