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

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

Arrays 3: search, unused elements and duplicates

1D arrays AS Level 16 min read

On this page
  1. What you need to be able to do
  2. Pattern 4: linear search
  3. Pattern 5: unused elements
  4. Pattern 6: duplicates (a loop inside a loop)
  5. Worked example: a membership list
  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, 9.2 Algorithms (Paper 2)
  • 10.2Write a linear search that stops as soon as the item is found, and returns its index or a value meaning “not found”.
  • 10.2Work with unused elements: count the used ones, find a free one, add and remove items.
  • 10.2Find duplicates with a nested loop.

You need: Arrays 2 (patterns 1-3) and the BOOLEAN flag from the toolkit page.

A linear search looks at the elements one by one, from the first, until it finds the item or runs out of elements. Two things can stop it, so the loop has two conditions: it is a WHILE (or REPEAT) loop, not a FOR.

index12345678
Code"K21""L07""B33""L07""Q90""A12""B33""Z01"
Searching for "B33": index 1 no, 2 no, 3 yes - stop. The second "B33" at index 7 is never looked at.
4Linear search with a flag

Keep going while there are elements left AND the item has not been found. Only move on (i ← i + 1) when this element is not the one. At the end the flag says which condition stopped the loop.

Use it when the question says search for …, find …, check whether … is in the array, returns the index of … or -1

Template
FUNCTION FindCode(Target : STRING) RETURNS INTEGER   DECLARE i : INTEGER   DECLARE Found : BOOLEAN   Found ← FALSE   i ← 1   WHILE i <= 8 AND Found = FALSE      IF Code[i] = Target THEN         Found ← TRUE      ELSE         i ← i + 1      ENDIF   ENDWHILE   IF Found = TRUE THEN      RETURN i   ELSE      RETURN -1   ENDIFENDFUNCTION

Trap Writing i ← i + 1 after the IF (not in the ELSE) moves i past the item it found, so the function returns the wrong index.

SituationWhat the loop doesReturns
Target is at index 3checks 1, 2, 3 - Found becomes TRUE, loop ends3
Target is the last elementchecks all 88
Target is not therechecks all 8, i becomes 9, the first condition stops the loop-1

Why -1? It can never be a real index of this array, so the caller can test IF FindCode(X) = -1 THEN. (A question may tell you to return 0 instead, or a BOOLEAN - always use what the description says.)

A FOR loop that looks at every element is fine when you must see them all (counting, totals). For “search”, examiners credit stopping as soon as it is found - a FOR loop that keeps going after finding it usually loses that mark.
Why does the WHILE test i <= 8 first, before Found = FALSE? When the item is missing, i reaches 9. Checking i <= 8 means we never use Code[9], which doesn't exist.

Pattern 5: unused elements

Real arrays are rarely full. The exam declares an array big enough for the worst case (“up to 100 members”) and says how an unused element is marked: usually the empty string "" for STRING arrays, or a value that can't be real data such as -1 or 0. Every loop over such an array must skip the unused elements.

index12345678
Member"Ali""""Sana""Omar""""""Hiba"""
4 used, 4 unused (""). The first free element is index 2.
The three unused-element jobs
// count the used elementsUsed ← 0FOR i ← 1 TO 8   IF Member[i] <> "" THEN      Used ← Used + 1   ENDIFNEXT i // find the first free element (-1 if the array is full)Free ← -1i ← 1WHILE i <= 8 AND Free = -1   IF Member[i] = "" THEN      Free ← i   ENDIF   i ← i + 1ENDWHILE // remove an item: mark its element as unused againMember[Pos] ← ""

Here the variable Free does the job of the flag: while it is still -1, nothing has been found. That is a common short-cut - one variable holds both “found yet?” and “where?”.

The exam question “Suggest how an unused array element could be indicated” wants: a value that cannot occur in the real data, e.g. an empty string for a name, or -1 for a mark. (It has been asked in exactly those words.)
When unused elements are mixed in, an average must divide by the number of used elements, and a minimum must ignore the unused value (or "" / -1 would always win).

Pattern 6: duplicates (a loop inside a loop)

To find values that appear more than once, compare every element with every later element. The outer loop picks one element (i); the inner loop looks at all the ones after it (j from i + 1).

index12345678
Code"K21""L07""B33""L07""Q90""A12""B33""Z01"
When i = 2 ("L07"), the inner loop j = 3 … 8 finds the same code at j = 4.
6Compare every pair once

Outer loop i from the first to the second-last; inner loop j from i + 1 to the last. Every pair is compared exactly once, and no element is compared with itself.

Use it when the question says occurs more than once, duplicate, repeated, unique, all different

Template
FUNCTION FirstRepeat() RETURNS STRING   DECLARE i, j : INTEGER   FOR i ← 1 TO 7      FOR j ← i + 1 TO 8         IF Code[i] = Code[j] THEN            RETURN Code[i]         ENDIF      NEXT j   NEXT i   RETURN ""ENDFUNCTION

Trap Starting j at 1 compares Code[i] with itself (always equal) and checks every pair twice.

Returning from inside the loops is allowed and is the simplest way to stop at the first repeat. Here the outer loop stops at 7 because when i = 8 there is nothing after it.

How many comparisons does pattern 6 make for 8 elements? 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 (every pair once).

Worked example: a membership list

This is the shape of many last questions: one global array with unused elements, and small modules that work together.

ModuleDescription
FindMember()
  • called with a name
  • returns the index of the element holding that name, or -1 if it is not in the array
AddMember()
  • called with a name
  • if the name is already in the array, or the array is full, returns FALSE
  • otherwise stores the name in the first unused element and returns TRUE
  • must use FindMember()
Example 1 · FindMember() and AddMember() (own example) ★★★ Hard
Q1Practice10 marks

A global array Member : ARRAY[1:100] OF STRING holds the names of a club's members. An unused element holds an empty string. Write pseudocode for the two modules in the table above.

1 Read it with me what is actually happening?

FindMember is a search. AddMember first asks FindMember whether the name is already there; if not, it looks for a gap and fills it. There are three ways AddMember can end: already there, stored, or no gap.

  • returns the index … or -1pattern 4
  • first unused elementpattern 5: the first i with Member[i] = ""
  • returns FALSE / TRUEAddMember is a FUNCTION … RETURNS BOOLEAN
  • must use FindMember()call it - don't search again by hand
2 What is it asking for? the target, part by part
  • 1FindMember(Name) → INTEGERsearch; -1 if missing
  • 2AddMember(Name) → BOOLEANthree outcomes: duplicate (FALSE), stored (TRUE), full (FALSE)
3 What do we know? everything the question gives us
  • 100elements: bounds 1:100
  • ""marks an unused element
  • A FOR loop with RETURN inside stops as soon as the item is found - an accepted way to write a search in a function.
  • “The array is full” = the loop ends without finding a "".
4 Plan the route work backwards from what we want
FindKey ideaAlready have itWork out firstTrap
  • FindAddMember(Name)
    • Already have itFindMember(Name) <> -1 means it is a duplicate → RETURN FALSE
    • Work out firstthe first i where Member[i] = "": store Name there, RETURN TRUE
    • TrapRETURN FALSE after the loop, not inside an ELSE (the first non-empty element would end the search)
Why must the full-array FALSE come after the loop?

Only once every element has been checked do we know there is no gap.

Could FindMember find an empty string?

Only if it were called with "" - the modules never do that.

5 Now solve it have a go on paper first, then open the worked solution
  1. FindMember: loop 1 to 100; if Member[i] = Name RETURN i; after the loop RETURN -1.
  2. AddMember: if FindMember(Name) <> -1 RETURN FALSE.
  3. Loop 1 to 100: at the first "" store Name and RETURN TRUE.
  4. After the loop RETURN FALSE (full).
Model answer
FUNCTION FindMember(Name : STRING) RETURNS INTEGER   DECLARE i : INTEGER   FOR i ← 1 TO 100      IF Member[i] = Name THEN         RETURN i      ENDIF   NEXT i   RETURN -1ENDFUNCTION FUNCTION AddMember(Name : STRING) RETURNS BOOLEAN   DECLARE i : INTEGER   IF FindMember(Name) <> -1 THEN      RETURN FALSE   ENDIF   FOR i ← 1 TO 100      IF Member[i] = "" THEN         Member[i] ← Name         RETURN TRUE      ENDIF   NEXT i   RETURN FALSEENDFUNCTION
6 Check it does the answer make sense?

Tested with Ali, "", Sana, …: adding Omar fills index 2 (TRUE), adding Sana again gives FALSE, Zain goes to index 4; a full array gives FALSE.

Practice: three levels

L1 Basic

Search, count used, count occurrences.

L1.1 Is it there?

Code : ARRAY[1:8] OF STRING is full. Input a code and output Found or Not found. Stop looking as soon as it is found.

Show the model answer
DECLARE Target : STRINGDECLARE Found : BOOLEANINPUT TargetFound ← FALSEi ← 1WHILE i <= 8 AND Found = FALSE   IF Code[i] = Target THEN      Found ← TRUE   ENDIF   i ← i + 1ENDWHILEIF Found = TRUE THEN   OUTPUT "Found"ELSE   OUTPUT "Not found"ENDIF

Here we only need yes/no, so i ← i + 1 can go after the IF: we never use i afterwards.

L1.2 Count the used

Score : ARRAY[1:10] OF INTEGER uses -1 for an unused element. Output how many elements are in use.

Show the model answer
Used ← 0FOR i ← 1 TO 10   IF Score[i] <> -1 THEN      Used ← Used + 1   ENDIFNEXT iOUTPUT Used

L1.3 How many times?

Using Score, output how many times the value 40 appears.

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

Counting every occurrence needs every element, so FOR is right here.

L2 Medium

Search and change; search backwards.

L2.1 Average of the used

Using Score (-1 = unused), output the average of the elements in use, or Empty if none are in use.

Show the model answer
Total ← 0Used ← 0FOR i ← 1 TO 10   IF Score[i] <> -1 THEN      Total ← Total + Score[i]      Used ← Used + 1   ENDIFNEXT iIF Used = 0 THEN   OUTPUT "Empty"ELSE   OUTPUT Total / UsedENDIF

The -1s must not be added, and the divisor is the number used, not 10.

L2.2 Remove a code

Write a procedure RemoveCode() that takes a code, and sets the first element of the global array Code that holds it to the empty string. If it is not there, output Not found.

Show the model answer
PROCEDURE RemoveCode(Target : STRING)   DECLARE i : INTEGER   DECLARE Done : BOOLEAN   Done ← FALSE   i ← 1   WHILE i <= 8 AND Done = FALSE      IF Code[i] = Target THEN         Code[i] ← ""         Done ← TRUE      ENDIF      i ← i + 1   ENDWHILE   IF Done = FALSE THEN      OUTPUT "Not found"   ENDIFENDPROCEDURE

Search (pattern 4) + mark as unused (pattern 5).

L2.3 Last occurrence

Write a function LastIndex() that takes an integer and returns the index of its last occurrence in the global array Score, or 0 if it is not there. Stop as soon as you can.

Hint

Which end of the array should the search start from?

Show the model answer
FUNCTION LastIndex(Value : INTEGER) RETURNS INTEGER   DECLARE i : INTEGER   i ← 10   WHILE i >= 1      IF Score[i] = Value THEN         RETURN i      ENDIF      i ← i - 1   ENDWHILE   RETURN 0ENDFUNCTION

Search backwards from the upper bound: the first match from the end is the last occurrence.

L3 Hard

Nested loops and unused elements together.

L3.1 All different?

Write a function AllDifferent() that returns TRUE if no value appears twice among the used elements of Score (-1 = unused; several -1s don't count as a repeat), otherwise FALSE.

Show the model answer
FUNCTION AllDifferent() RETURNS BOOLEAN   DECLARE i, j : INTEGER   FOR i ← 1 TO 9      IF Score[i] <> -1 THEN         FOR j ← i + 1 TO 10            IF Score[j] = Score[i] THEN               RETURN FALSE            ENDIF         NEXT j      ENDIF   NEXT i   RETURN TRUEENDFUNCTION

Pattern 6 with pattern 5: skip an unused Score[i]. (Score[j] can't equal a used Score[i] if it is -1.)

L3.2 Count each code once

The global array Code may contain repeats. Write a procedure ShowCounts() that outputs each different code once, with how many times it appears, in the order they first appear (e.g. L07 2).

Hint

Split it: first decide whether Code[i] is the first time this code appears.

Show the model answer
PROCEDURE ShowCounts()   DECLARE i, j, Count : INTEGER   DECLARE Seen : BOOLEAN   FOR i ← 1 TO 8      Seen ← FALSE      FOR j ← 1 TO i - 1         IF Code[j] = Code[i] THEN            Seen ← TRUE         ENDIF      NEXT j      IF Seen = FALSE THEN         Count ← 0         FOR j ← i TO 8            IF Code[j] = Code[i] THEN               Count ← Count + 1            ENDIF         NEXT j         OUTPUT Code[i], " ", Count      ENDIF   NEXT iENDPROCEDURE

For each element: has this code appeared EARLIER (j before i)? If not, it is new: count it from here to the end. When i = 1 the first inner loop (1 TO 0) runs zero times.

L3.3 Booking seats

Seat : ARRAY[1:40] OF STRING holds the name of the passenger in each seat of a bus, or "" if it is free. Write a function BookTogether() that takes a name and books the first two free seats next to each other (n and n + 1) for that passenger. It returns the first seat number, or -1 if there are no two free seats together.

Show the model answer
FUNCTION BookTogether(Name : STRING) RETURNS INTEGER   DECLARE n : INTEGER   FOR n ← 1 TO 39      IF Seat[n] = "" AND Seat[n + 1] = "" THEN         Seat[n] ← Name         Seat[n + 1] ← Name         RETURN n      ENDIF   NEXT n   RETURN -1ENDFUNCTION

The loop stops at 39 because it looks at n + 1. A free pair is two unused elements side by side.

Mistakes that lose marks

MistakeWrite this instead
A FOR loop that carries on after the item is foundWHILE with a flag, or RETURN as soon as it is found
Returning “not found” inside the loop's ELSEDecide “not found” only after the loop has checked everything
Counting / averaging the unused elements tooSkip them: IF Name[i] <> "" THEN
Inner loop j starting at 1FOR j ← i + 1 TO Upper (each pair once, never with itself)
Reading A[i + 1] up to the upper boundStop at upper bound - 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.

1Why does a search return -1 rather than 0 when the array starts at index 0?Show answer

0 would be a real index there; -1 can never be one.

2How does a variable like Free (starting at -1) replace a BOOLEAN flag?Show answer

While it is -1 nothing has been found; once it holds an index we both know it was found and where.

3Why does the inner loop of pattern 6 start at i + 1?Show answer

Pairs before i were already compared when the outer loop was at the smaller index, and an element must not be compared with itself.

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

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