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

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

Arrays 2: count, total, average and the highest

1D arrays AS Level 15 min read

On this page
  1. What you need to be able to do
  2. One loop, three questions
  3. Pattern 1: count the elements that match
  4. Pattern 2: total and average
  5. Pattern 3: the highest value and where it is
  6. As functions using a global array
  7. Worked example: a week of sales
  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, 9.2 Algorithms (Paper 2)
  • 10.2Go through an array and count the elements that match a condition.
  • 10.2Work out a total and an average of the elements.
  • 10.2Find the highest or lowest value and its index.
  • 11.3Write each of these as a function that uses a global array.

You need: Arrays 1 (index vs value, the FOR loop over every element).

One loop, three questions

Every pattern on this page uses the same loop you already know. What changes is the variable you keep beside the loop: a counter, a running total, or the best-so-far. All the examples use this array of 10 test marks:

index12345678910
Mark56813490478112687550
A global array Mark : ARRAY[1:10] OF INTEGER, already filled.

Pattern 1: count the elements that match

1Count

A counter starts at 0 before the loop and goes up by 1 each time an element passes the test.

Use it when the question says how many …, the number of …

index12345678910
Mark56813490478112687550
Green = passes the test Mark[i] >= 50. There are 7 of them.
Template
Count ← 0FOR i ← 1 TO 10   IF Mark[i] >= 50 THEN      Count ← Count + 1   ENDIFNEXT iOUTPUT Count

Trap Count ← 0 inside the loop resets it every time. And the test is on Mark[i] (the value), not on i.

See the trace table for pattern 1
iMark[i]Count
1561
2812
334
4903
547
6814
712
8685
9756
10507

Count only changes on the rows where Mark[i] is 50 or more.

Pattern 2: total and average

2Total and average

A running total starts at 0 and has every element added to it. The average is the total divided by how many values were added - worked out once, after the loop.

Use it when the question says the total …, the average …, the mean …

index12345678910
Mark56813490478112687550
When i = 4, Total ← Total + 90.
Template
Total ← 0FOR i ← 1 TO 10   Total ← Total + Mark[i]NEXT iAverage ← Total / 10OUTPUT "Total ", Total, " average ", Average

Trap Dividing inside the loop. And if you only add some elements (e.g. only the passes), divide by the count of those, not by 10.

The average of only the marks that are 50 or more: what do you need beside the total? A counter of how many were added (pattern 1 and 2 in the same loop), then Total / Count - and check Count is not 0 first.
Patterns 1 and 2 together: the average of the passes only
Total ← 0Count ← 0FOR i ← 1 TO 10   IF Mark[i] >= 50 THEN      Total ← Total + Mark[i]      Count ← Count + 1   ENDIFNEXT iIF Count > 0 THEN   OUTPUT Total / CountELSE   OUTPUT "No passes"ENDIF
Dividing by a count that might be 0 is a run-time error. Whenever the count depends on the data, test Count > 0 before dividing.

Pattern 3: the highest value and where it is

3Highest (or lowest) and its index

Start with the first element as the best so far, then compare every other element with it. When one is bigger, remember its value and its index.

Use it when the question says the highest …, the largest …, the cheapest …, which student …, the position of …

index12345678910
Mark56813490478112687550
Max goes 56 → 81 (index 2) → 90 (index 4). The second 81 is not bigger, so nothing changes.
Template
Max ← Mark[1]Pos ← 1FOR i ← 2 TO 10   IF Mark[i] > Max THEN      Max ← Mark[i]      Pos ← i   ENDIFNEXT iOUTPUT "Highest ", Max, " at index ", Pos

Trap Starting Max at 0 fails when every value is negative; starting at the first element always works. For the lowest, start the same way and use <.

Trace table for pattern 3
iMark[i]MaxPos
281561
334812
490904
547
681
712
868
975
1050

Why remember Pos? Because the question often wants who or which, not just the value - and with parallel arrays (Arrays 5) the index of the highest mark is also the index of that student's name: OUTPUT Name[Pos].

Two students both got the highest mark. With >, which index does Pos end on? With >=? With > Pos stays on the first one; with >= it moves on to the last one.

As functions using a global array

In the exam these patterns are almost always inside a module. The array is global, so the function just uses it; the description tells you what comes in as parameters and what is returned.

ModuleDescription
CountAbove()
  • called with an integer parameter Limit
  • returns the number of elements of the global array Mark that are greater than Limit
Pattern 1 as a function
FUNCTION CountAbove(Limit : INTEGER) RETURNS INTEGER   DECLARE Count, i : INTEGER   Count ← 0   FOR i ← 1 TO 10      IF Mark[i] > Limit THEN         Count ← Count + 1      ENDIF   NEXT i   RETURN CountENDFUNCTION
Same loop as before. The differences: a header with the parameter, local declarations, and RETURN Count instead of OUTPUT.

Worked example: a week of sales

Example 1 · BestDay() and Report() (own example) ★★ Medium
Q1Practice9 marks

A global array Sales : ARRAY[1:7] OF INTEGER holds a shop's sales for each day of a week (day 1 = Monday). It has already been filled.

ModuleDescription
BestDay()
  • returns the day number with the highest sales
  • if two days have the same highest sales, returns the earlier day
Report()
  • outputs the total sales for the week
  • outputs the number of days with no sales
  • outputs the best day, using BestDay()

Write pseudocode for both modules.

1 Read it with me what is actually happening?

The array is filled already: our job is only to look at it. BestDay needs the highest value but must give back WHERE it is. Report does a total and a count in one pass, then asks BestDay.

  • returns the day numberthe index of the highest value, not the value
  • the earlier dayuse > (not >=) so a tie doesn't move it
  • outputsReport is a PROCEDURE with OUTPUT; it has no parameters
2 What is it asking for? the target, part by part
  • 1BestDay() → INTEGERpattern 3, keeping only the index
  • 2Reportpattern 2 + pattern 1 in one loop, then call BestDay()
3 What do we know? everything the question gives us
  • 7days: bounds 1:7
  • globalSales is used directly, not passed in
  • Sales[Best] is the best value so far - we don't need a separate Max variable if we keep the index.
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • Findthe three outputs
    • Work out firstBestDay: Best ← 1, compare Sales[Day] > Sales[Best]
      • Trap>= would return the later of two equal days
    • Key ideaone loop: Total + Sales[Day]; Zero + 1 when Sales[Day] = 0
    • Already have itBestDay() gives the day: OUTPUT it
Why does BestDay start the loop at 2?

Day 1 is already the best so far; comparing it with itself does nothing.

How is BestDay() used in Report?

Its value goes straight into OUTPUT: it is a function, so no CALL.

5 Now solve it have a go on paper first, then open the worked solution
  1. BestDay: Best ← 1; loop 2 to 7; if Sales[Day] > Sales[Best] then Best ← Day; RETURN Best.
  2. Report: Total ← 0, Zero ← 0; loop 1 to 7 adding to Total and counting zeros; output Total, Zero and BestDay().
Model answer
FUNCTION BestDay() RETURNS INTEGER   DECLARE Day, Best : INTEGER   Best ← 1   FOR Day ← 2 TO 7      IF Sales[Day] > Sales[Best] THEN         Best ← Day      ENDIF   NEXT Day   RETURN BestENDFUNCTION PROCEDURE Report()   DECLARE Day, Total, Zero : INTEGER   Total ← 0   Zero ← 0   FOR Day ← 1 TO 7      Total ← Total + Sales[Day]      IF Sales[Day] = 0 THEN         Zero ← Zero + 1      ENDIF   NEXT Day   OUTPUT "Total sales: ", Total   OUTPUT "Days with no sales: ", Zero   OUTPUT "Best day: ", BestDay()ENDPROCEDURE
6 Check it does the answer make sense?

With sales 120, 0, 340, 95, 340, 210, 0: total 1105, 2 days with no sales, best day 3 (day 5 ties at 340 but is later). Our checker agrees.

Practice: three levels

L1 Basic

One pattern on its own.

L1.1 Count the zeros

Score : ARRAY[1:20] OF INTEGER is full. Output how many elements are 0.

Show the model answer
Count ← 0FOR i ← 1 TO 20   IF Score[i] = 0 THEN      Count ← Count + 1   ENDIFNEXT iOUTPUT Count

L1.2 Total

Temp : ARRAY[1:12] OF INTEGER holds the temperature at midday for 12 days. Output the total and the average.

Show the model answer
Total ← 0FOR i ← 1 TO 12   Total ← Total + Temp[i]NEXT iOUTPUT TotalOUTPUT Total / 12

L1.3 Lowest

Using the same Temp array, output the lowest temperature.

Show the model answer
Low ← Temp[1]FOR i ← 2 TO 12   IF Temp[i] < Low THEN      Low ← Temp[i]   ENDIFNEXT iOUTPUT Low

Pattern 3 with <.

L2 Medium

Two patterns in one loop, or one with a twist.

L2.1 Hot days

Using Temp, output how many days were 25 or hotter, and the average temperature of those days only.

Show the model answer
Count ← 0Total ← 0FOR i ← 1 TO 12   IF Temp[i] >= 25 THEN      Count ← Count + 1      Total ← Total + Temp[i]   ENDIFNEXT iOUTPUT CountIF Count > 0 THEN   OUTPUT Total / CountENDIF

Divide by the number of hot days, not by 12.

L2.2 Hottest day

Output the highest temperature and the day number it happened on. If it happened on more than one day, output the last such day.

Show the model answer
Max ← Temp[1]Pos ← 1FOR i ← 2 TO 12   IF Temp[i] >= Max THEN      Max ← Temp[i]      Pos ← i   ENDIFNEXT iOUTPUT Max, " on day ", Pos

>= lets an equal value move Pos on, so the last of the equal days wins (30 on days 4 and 6 → day 6).

L2.3 Range

Write a function Range() that returns the difference between the highest and the lowest value in the global array Temp. Use one loop.

Show the model answer
FUNCTION Range() RETURNS INTEGER   DECLARE Max, Min, i : INTEGER   Max ← Temp[1]   Min ← Temp[1]   FOR i ← 2 TO 12      IF Temp[i] > Max THEN         Max ← Temp[i]      ENDIF      IF Temp[i] < Min THEN         Min ← Temp[i]      ENDIF   NEXT i   RETURN Max - MinENDFUNCTION

Two separate IFs (not ELSE): one element can't be both, but each must be checked.

L3 Hard

As modules, with two loops or two patterns.

L3.1 Above average

Write a procedure AboveAverage() that outputs every value in the global array Mark : ARRAY[1:10] OF INTEGER that is above the average of the array, and then how many there were.

Hint

Can you decide whether Mark[1] is above average before you have seen Mark[10]?

Show the model answer
PROCEDURE AboveAverage()   DECLARE i, Total, Count : INTEGER   DECLARE Average : REAL   Total ← 0   FOR i ← 1 TO 10      Total ← Total + Mark[i]   NEXT i   Average ← Total / 10   Count ← 0   FOR i ← 1 TO 10      IF Mark[i] > Average THEN         OUTPUT Mark[i]         Count ← Count + 1      ENDIF   NEXT i   OUTPUT CountENDPROCEDURE

Two loops: the average must be known before any element can be compared with it.

L3.2 Second highest

Write a function SecondHighest() that returns the second highest DIFFERENT value in the global array Mark (for 56, 81, 34, 90, 47, 81, … it is 81). You may assume the array has at least two different values.

Hint

Do it in two passes: what does the first pass find?

Show the model answer
FUNCTION SecondHighest() RETURNS INTEGER   DECLARE i, Max, Second : INTEGER   Max ← Mark[1]   FOR i ← 2 TO 10      IF Mark[i] > Max THEN         Max ← Mark[i]      ENDIF   NEXT i   Second ← -1   FOR i ← 1 TO 10      IF Mark[i] < Max AND Mark[i] > Second THEN         Second ← Mark[i]      ENDIF   NEXT i   RETURN SecondENDFUNCTION

First find the highest. Then find the highest of the values that are below it. (Second starts at -1, safe because marks are never negative.)

L3.3 Longest run

Rain : ARRAY[1:30] OF BOOLEAN is TRUE for each day of a month on which it rained. Write a function LongestDry() that returns the largest number of dry days in a row.

Show the model answer
FUNCTION LongestDry() RETURNS INTEGER   DECLARE i, Run, Best : INTEGER   Run ← 0   Best ← 0   FOR i ← 1 TO 30      IF Rain[i] = FALSE THEN         Run ← Run + 1         IF Run > Best THEN            Best ← Run         ENDIF      ELSE         Run ← 0      ENDIF   NEXT i   RETURN BestENDFUNCTION

A counter that resets (Run) plus a best-so-far (Best): patterns 1 and 3 working together.

Mistakes that lose marks

MistakeWrite this instead
Max ← 0 (or Min ← 999) as the starting valueMax ← Mark[1] and loop from 2
Remembering the value but not the index when the question asks “which”Keep Pos ← i beside Max ← Mark[i]
Total / 10 when only some values were addedDivide by the count of values added, and check it is not 0
Outputting inside the loop when one answer is wantedOutput (or RETURN) once, after the loop
Comparing i > Max (the index)Compare the value: Mark[i] > Max

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 does pattern 3 loop from 2 and not from 1?Show answer

Element 1 is already the best so far; comparing it with itself changes nothing.

2How do you find the lowest value AND its index?Show answer

Exactly like the highest: Min ← A[1], Pos ← 1, loop from 2, and when A[i] < Min set Min ← A[i] and Pos ← i.

3Why do some tasks need two loops over the same array?Show answer

When the test depends on the whole array (above the average, below the highest), the first loop must finish before the second one can compare.

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

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