Paper 2: Pseudocode step by step (arrays, functions, procedures)
Arrays 3: search, unused elements and duplicates
What you need to be able to do
- 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.
Pattern 4: linear search
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.
| index | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Code | "K21" | "L07" | "B33" | "L07" | "Q90" | "A12" | "B33" | "Z01" |
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
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 ENDIFENDFUNCTIONTrap 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.
| Situation | What the loop does | Returns |
|---|---|---|
| Target is at index 3 | checks 1, 2, 3 - Found becomes TRUE, loop ends | 3 |
| Target is the last element | checks all 8 | 8 |
| Target is not there | checks 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.)
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.
| index | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Member | "Ali" | "" | "Sana" | "Omar" | "" | "" | "Hiba" | "" |
// 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?”.
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).
| index | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Code | "K21" | "L07" | "B33" | "L07" | "Q90" | "A12" | "B33" | "Z01" |
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
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 ""ENDFUNCTIONTrap 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.
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.
| Module | Description |
|---|---|
FindMember() |
|
AddMember() |
|
Example 1 · FindMember() and AddMember() (own example) ★★★ Hard
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.
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
- 1FindMember(Name) → INTEGER
- 2AddMember(Name) → BOOLEAN
- 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 "".
- 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
- FindMember: loop 1 to 100; if Member[i] = Name RETURN i; after the loop RETURN -1.
- AddMember: if FindMember(Name) <> -1 RETURN FALSE.
- Loop 1 to 100: at the first "" store Name and RETURN TRUE.
- After the loop RETURN FALSE (full).
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 FALSEENDFUNCTIONTested 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"ENDIFHere 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 UsedL1.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 CountCounting 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 / UsedENDIFThe -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" ENDIFENDPROCEDURESearch (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 0ENDFUNCTIONSearch 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 TRUEENDFUNCTIONPattern 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 iENDPROCEDUREFor 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 -1ENDFUNCTIONThe loop stops at 39 because it looks at n + 1. A free pair is two unused elements side by side.
Mistakes that lose marks
| Mistake | Write this instead |
|---|---|
| A FOR loop that carries on after the item is found | WHILE with a flag, or RETURN as soon as it is found |
| Returning “not found” inside the loop's ELSE | Decide “not found” only after the loop has checked everything |
| Counting / averaging the unused elements too | Skip them: IF Name[i] <> "" THEN |
| Inner loop j starting at 1 | FOR j ← i + 1 TO Upper (each pair once, never with itself) |
Reading A[i + 1] up to the upper bound | Stop at upper bound - 1 |
Can I do this?
- I can write a linear search that stops when found and returns the index or -1.
- I can count, find, add and remove with unused elements, and skip them in totals.
- I can write a nested loop that compares every pair once.
- I can combine search + unused elements in modules like AddMember().
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