Year 12

AQA A level Computer Science [P2] Pseudocode Notes

Pseudocode & Problem Solving

— Computer Science · A Level (9618) Paper 2 · Part C: Syntax · Selection · Loops · Arrays · Files · Modules · Bubble Sort —
★ Exam Tip: Paper 2 now tests 7–9 mark pseudocode questions far more than theory. This is where your marks are. Forget Python syntax completely — pseudocode has its own keywords. Use the keywords exactly, indent, and declare every variable.
Note on arrows: the board writes assignment as "=" or "<-----". Thepseudocode symbol is ← (type <- ). Use ← in the exam. All code in these notes uses ←.

1. Basic Syntax

Operator Meaning
* multiplication
/ division
+ addition
− subtraction
& string concatenation (joins strings) — not +

Variables and input

Declaration is necessary: DECLARE name : TYPE. Question: input 2 numbers and print their sum.

DECLARE N1, N2, Sum : INTEGER INPUT N1 INPUT N2 Sum ← N1 + N2 OUTPUT Sum
Prompt rule: In Python the prompt went inside input(). In pseudocode you cannot — you must print a message first, then input. "Prompt the user" = display a message, then INPUT.
PRINT ("Type two numbers") INPUT N1, N2
Careful: brackets after PRINT are compulsory (sir). Quotation marks around the message — without them it is treated as a variable and the message won't show. PRINT Sum shows the value of Sum. "Suitable prompt" = any clear message.

String concatenation: FullName ← FirstName & LastName (FirstName "Taha", LastName "Ali"). Python used "+".

Examiner always tells you exactly what to input / whether to prompt — read every word of the question.

2. Selection Statements

Two selection statements: IF … THEN … ELSE … ENDIF and CASE … OF … OTHERWISE … ENDCASE.

IF syntaxIF (condition) THEN instruction ELSEIF (condition) THEN instruction ELSE instruction ENDIF
AND / OR: AND — both conditions must be true. OR — any one condition must be true.
practicelargest of three numbers
DECLARE A, B, C, Large : INTEGER INPUT A, B, C IF A > B AND A > C THEN Large ← A ELSEIF B > C THEN Large ← B ELSE Large ← C ENDIF OUTPUT Large
questionpositive / negative / zero
INPUT Number IF Number > 0 THEN OUTPUT "Positive" ELSEIF Number < 0 THEN OUTPUT "Negative" ELSE OUTPUT "Zero" ENDIF

CASE … OF … OTHERWISE … ENDCASE

Use when there are a lot of choices / conditions.

CASE Marks OF > 80 : Grade ← "A" > 70 : Grade ← "B" < 50 : Grade ← "F" OTHERWISE Grade ← "U" ENDCASE

3. Built-in Functions & String Comparison

Function What it does Example
LENGTH(s) number of characters LENGTH("Eric") → 4
LEFT(s, n) first n characters LEFT("Papers", 3) → "Pap"
RIGHT(s, n) last n characters RIGHT("Papers", 3) → "ers"
MID(s, start, n) n characters from position start (first character = 1) MID("Papers", 2, 3) → "ape"
INT(x) integer part (drops decimals) INT(24.8) → 24
ASC(c) / CHR(n) character ↔ ASCII code ASC('C') → 67
NUM_TO_STR / STR_TO_NUM convert between number and string STR_TO_NUM("27") → 27
ISNUM(s) TRUE if the string value is all numbers ISNUM("123") → TRUE
String comparison: pseudocode lets you compare strings — "Z" > "A". To test a capital letter: Character >= "A" AND Character <= "Z".
built-in functions Qevaluate · 5 marks

Title = "101 tricks with spaghetti" · Version = 'C' · Author = "Eric Peapod" · PackSize = 4 · WeightEach = 6.2 · Paperback = TRUE. If invalid write ERROR.

Expression Evaluates to
MID(Title, 5, 3) & RIGHT(Author, 3) "tri" & "pod" = "tripod"
INT(WeightEach * PackSize) INT(24.8) = 24
PackSize >= 4 AND WeightEach < 6.2 TRUE AND FALSE = FALSE
LEFT(Author, ASC(Version) − 65) ASC('C') = 67 → LEFT(Author, 2) = "Er"
RIGHT(Title, (LENGTH(Author) − 6)) LENGTH = 11 → RIGHT(Title, 5) = "hetti"
practicepassword check

Password is correct if: ① 1st character is a capital ② 2nd–4th characters are numbers ③ length is 9. Take the password and print "Approve" if all conditions are met.

DECLARE Pass : STRING PRINT ("Enter password") INPUT Pass IF LENGTH(Pass) = 9 AND LEFT(Pass, 1) >= "A" AND LEFT(Pass, 1) <= "Z" AND ISNUM(MID(Pass, 2, 3)) = TRUE THEN PRINT ("Approve") ELSE PRINT ("Reject") ENDIF

4. Loops (Repetition)

Repetition of instructions is called a loop. Three types:

FOR … TO … NEXT WHILE … DO … ENDWHILE REPEAT … UNTIL
count-controlled
repetition known
fixed iteration — always executes
no condition · no Count ← Count + 1
pre-condition (conditional)
repetition unknown
runs while the condition is TRUE — may run 0 times
use Count ← Count + 1
post-condition (conditional)
repetition unknown
runs until the condition becomes TRUE — always runs at least once
use Count ← Count + 1
questioninput 500 names, print "Hello Name", with prompt — all three loops
FOR
DECLARE Count : INTEGER DECLARE Names, Final : STRING FOR Count ← 1 TO 500 PRINT ("Enter name") INPUT Names Final ← "Hello " & Names PRINT Final ENDFOR
WHILE
Count ← 0 WHILE Count < 500 DO Count ← Count + 1 PRINT ("Enter name") INPUT Names Final ← "Hello " & Names PRINT Final ENDWHILE
REPEAT
Count ← 0 REPEAT Count ← Count + 1 PRINT ("Enter name") INPUT Names Final ← "Hello " & Names PRINT Final UNTIL Count = 500

5. Programming Techniques

Technique Outside the loop Inside the loop
Sum Sum ← 0 Sum ← Sum + Number
Counting Count ← 0 Count ← Count + 1
Largest Large ← 0 IF Number > Large THEN Large ← Number
Smallest Small ← 9999 IF Number < Small THEN Small ← Number
Careful: initialise outside the loop — inside it would reset every time. Large starts at 0 (or lower than any possible value), Small starts very high. Print results outside the loop too.
questionsum of 10 numbers
DECLARE Sum, Count, Number : INTEGER Sum ← 0 FOR Count ← 1 TO 10 INPUT Number Sum ← Sum + Number ENDFOR OUTPUT Sum
questioninput 500 numbers — how many are positive?
Positive ← 0 FOR Count ← 1 TO 500 INPUT N1 IF N1 > 0 THEN Positive ← Positive + 1 ENDIF ENDFOR OUTPUT Positive
practice (board: 499 numbers)count positive, negative and zero
Positive ← 0 Negative ← 0 Zero ← 0 FOR Count ← 1 TO 499 INPUT Number IF Number > 0 THEN Positive ← Positive + 1 ELSEIF Number < 0 THEN Negative ← Negative + 1 ELSE Zero ← Zero + 1 ENDIF ENDFOR PRINT ("Positive numbers count: ", Positive) PRINT ("Negative numbers count: ", Negative) PRINT ("Zero numbers count: ", Zero)
questioninput 5 numbers, print the largest
Large ← 0 FOR Count ← 1 TO 5 INPUT Num IF Num > Large THEN Large ← Num ENDIF ENDFOR OUTPUT Large

board stops after ENDFOR — remember to output Large outside the loop.

Flag looping

Whenever we need to stop the loop or make the code efficient, use a flag and a conditional loop.

Flag ← TRUE WHILE Flag = TRUE DO INPUT Response IF Response = "No" THEN Flag ← FALSE ENDIF ENDWHILE
questioninput until the password is correct (1st character a capital)
DECLARE Correct : BOOLEAN DECLARE Pass, FirstCharacter : STRING Correct ← FALSE WHILE Correct = FALSE DO PRINT ("Enter your password") INPUT Pass FirstCharacter ← LEFT(Pass, 1) IF FirstCharacter >= "A" AND FirstCharacter <= "Z" THEN PRINT ("Approve") Correct ← TRUE ELSE PRINT ("Re-write your password") ENDIF ENDWHILE
practiceinput numbers until 0 is typed — find the average
Total ← 0 Count ← 0 INPUT Number WHILE Number <> 0 DO Total ← Total + Number Count ← Count + 1 INPUT Number ENDWHILE IF Count > 0 THEN OUTPUT Total / Count ENDIF

sentinel 0 is not added; check Count > 0 to avoid dividing by zero (a run-time error).

6. Arrays

Array: stores multiple values of the same datatype; each value sits at a position called an index.

"Pappan""Banto""Bano""Pappu""Ahmed""Taha" 543210 Upper boundLower boundNames
Names[3] = "Bano" · Names[0] = "Taha" · Names[5] = "Pappan" · Names[6] would be out of bounds
Declare a 1D arrayDECLARE NameOfArray : ARRAY[LowerBound : UpperBound] OF DataType

e.g. array "FoodItems", bounds 1–6, strings: DECLARE FoodItems : ARRAY[1:6] OF STRING

question565 names input by the user
DECLARE Names : ARRAY[1:565] OF STRING FOR Index ← 1 TO 565 INPUT Names[Index] ENDFOR
practice100 elements all set to "No Data" (ResultArray)
DECLARE ResultArray : ARRAY[1:100] OF STRING FOR Index ← 1 TO 100 ResultArray[Index] ← "No Data" ENDFOR

First access the individual element (ResultArray[5] ← "No Data"), then wrap it in a loop.

Linear search

Each element is compared with the value to find, in order from lower bound to upper bound, until the item is found or the upper bound is reached. Use a selection statement inside the loop.

questionSTNames (500 names): at which index is "Bano"?
DECLARE Index : INTEGER FOR Index ← 1 TO 500 IF STNames[Index] = "Bano" THEN PRINT Index ENDIF ENDFOR
practiceSearchBox (500 strings): how many times is "Empty" repeated?
DECLARE Index, EmptyCount : INTEGER EmptyCount ← 0 FOR Index ← 1 TO 500 IF SearchBox[Index] = "Empty" THEN EmptyCount ← EmptyCount + 1 ENDIF ENDFOR PRINT EmptyCount

same idea as the Structured-English example in Part B.

2-dimensional arrays

A grid (matrix) of rows and columns; each element identified by its row and column values. Commonly used for images, game boards, tables.

0123012345 rows × 4 columns
[row, column] — first index = row, second = column
Declare a 2D arrayDECLARE NameOfArray : ARRAY[LB : UB, LB : UB] OF DataType
                             rows       columns
DECLARE Numbers : ARRAY[1:4, 1:3] OF INTEGER
Slide typo: the practice answer for "545 rows × 250 columns of STRING" must be DECLARE Names : ARRAY[1:545, 1:250] OF STRING (the slide wrote INTEGERS). The data type is the singular keyword INTEGER / STRING.

Nested loop = loop within a loop. FOR Count ← 1 TO 10 → FOR Index ← 1 TO 5 → PRINT "PAPERSDOCK" runs 10 × 5 = 50 times. For 2D arrays: outer loop = rows, inner loop = columns.

e.g. Number[2,1] = 21 · Number[4,1] = 78 · Number[3,3] = 54 (row first, then column).

question500 × 45 string array EmptyBox — initialise all elements
DECLARE EmptyBox : ARRAY[1:500, 1:45] OF STRING FOR RowIndex ← 1 TO 500 FOR ColumnIndex ← 1 TO 45 EmptyBox[RowIndex, ColumnIndex] ← "" ENDFOR ENDFOR
questionSearchBox 500 × 30: how many "Empty"?
Count ← 0 FOR Row ← 1 TO 500 FOR Column ← 1 TO 30 IF SearchBox[Row, Column] = "Empty" THEN Count ← Count + 1 ENDIF ENDFOR ENDFOR PRINT (Count)
practiceSearchBox 500 × 356: replace "Empty" with "Bano"
FOR Row ← 1 TO 500 FOR Column ← 1 TO 356 IF SearchBox[Row, Column] = "Empty" THEN SearchBox[Row, Column] ← "Bano" ENDIF ENDFOR ENDFOR

slide used 30 columns and printed Count — the question says 356 columns and no output.

7. Text Files

Purpose of a file: to store data permanently (not lost when the program ends).

READ mode WRITE mode APPEND mode
when you only want to read data from an existing file to write data to a new file — creates the file, all previous data deleted, written from scratch to add data to the end of an existing file
Write / AppendOPENFILE "File.txt" FOR WRITE
  (or FOR APPEND)
WRITEFILE "File.txt", "String"/Variable
CLOSEFILE "File.txt"
ReadOPENFILE "File.txt" FOR READ
READFILE "File.txt", Variable
CLOSEFILE "File.txt"
READFILE reads one line into the variable
questionwrite 700 names from array School into a new file Names.txt
DECLARE Index : INTEGER DECLARE Name : STRING OPENFILE "Names.txt" FOR WRITE FOR Index ← 1 TO 700 Name ← School[Index] WRITEFILE "Names.txt", Name ENDFOR CLOSEFILE "Names.txt"
practice54 employees input ID (4 chars) + name e.g. "2675Bano" — store only the ID in New.txt
DECLARE Value, ID : STRING OPENFILE "New.txt" FOR WRITE FOR Index ← 1 TO 54 INPUT Value ID ← LEFT(Value, 4) WRITEFILE "New.txt", ID ENDFOR CLOSEFILE "New.txt"
questionadd one more ID "2356" to the existing New.txt
OPENFILE "New.txt" FOR APPEND WRITEFILE "New.txt", "2356" CLOSEFILE "New.txt"
questionprint all 500 lines of Sample.txt
OPENFILE "Sample.txt" FOR READ FOR Index ← 1 TO 500 READFILE "Sample.txt", Filedata PRINT Filedata ENDFOR CLOSEFILE "Sample.txt"
EOF concept: to read from beginning to end when you don't know how many lines there are, use a conditional loop. A text file has a special End-Of-File marker; EOF("file") becomes TRUE when it is reached.
OPENFILE "Sample.txt" FOR READ WHILE NOT EOF("Sample.txt") DO READFILE "Sample.txt", Filedata PRINT Filedata ENDWHILE CLOSEFILE "Sample.txt"

Slide wrote "CLOSEWHILE" — the correct keyword is ENDWHILE, then CLOSEFILE.

practicemusic file: each line = Title (40 chars) · ArtistName (40 chars) · Location (8 chars)

User inputs a location; print the title and artist of every CD at that location and how many CDs there are.

Total ← 0 OPENFILE "MyMusic" FOR READ PRINT ("Input location") INPUT CDSearch WHILE NOT EOF("MyMusic") DO READFILE "MyMusic", FileData IF RIGHT(FileData, 8) = CDSearch THEN CDTitle ← LEFT(FileData, 40) CDArtist ← MID(FileData, 41, 40) PRINT (CDTitle & " " & CDArtist) Total ← Total + 1 ENDIF ENDWHILE PRINT (Total & " CDs found") CLOSEFILE "MyMusic"

fixed-width fields: LEFT 40 = title · MID start 41, length 40 = artist · RIGHT 8 = location.

8. Functions & Procedures

Function Procedure
returns a value does not return a value
Print vs Return: PRINT / OUTPUT only displays a value. RETURN sends the value back to the calling code so it can be stored or used in another calculation.
Function headerFUNCTION Name(Param : TYPE, Param : TYPE) RETURNS TYPE
  …
  RETURN value
ENDFUNCTION
Procedure headerPROCEDURE Name(Param : TYPE, Param : TYPE)
  …
ENDPROCEDURE
called with CALL Name(...)
Note: the procedure-header slide shows "RETURN Datatype" — a procedure has no return type.
questionmodule Square — takes an integer and returns its square
FUNCTION Square(BYVAL x : INTEGER) RETURNS INTEGER Sq ← x * x RETURN Sq ENDFUNCTION
boat hire (past paper)ListAvailable() — 7–8 marks

Global arrays: HireTime (STRING, "10:15" or "Available") · Duration (INTEGER minutes) · Cost (REAL) — 10 boats. ListAvailable() is called with a STRING start time; it outputs each boat number that will be available at that time (currently not on hire, or due back before the start time), the number of boats available, or a suitable message if none. AddTime(time, minutes) returns the new time as a STRING.

PROCEDURE ListAvailable(StartTime : STRING) BoatNumAvailable ← 0 FOR Index ← 1 TO 10 Available ← FALSE IF HireTime[Index] = "Available" THEN Available ← TRUE ELSE TimeBack ← AddTime(HireTime[Index], Duration[Index]) IF TimeBack < StartTime THEN Available ← TRUE ENDIF ENDIF IF Available = TRUE THEN OUTPUT "Boat ", Index, " is available" BoatNumAvailable ← BoatNumAvailable + 1 ENDIF ENDFOR IF BoatNumAvailable > 0 THEN OUTPUT "There are ", BoatNumAvailable, " boats available" ELSE OUTPUT "Sorry, no boats" ENDIF ENDPROCEDURE

board header wrote StartTime : INTEGER — the question says a STRING. Initialise Available ← FALSE inside the FOR loop (for each boat).

9. Bubble Sort

An algorithm to arrange an array in ascending or descending order.

Swapping — the classic mistake: you must use a temporary variable.
Incorrectarray ← [9, 0]array[0] ← array[1]array[1] ← array[0]both elements become 0 — the 9 is lost!
Correctarray ← [9, 0]temp ← array[0]array[0] ← array[1]array[1] ← temp

Two loops: the inner loop compares neighbours and swaps — after each pass one value is in its final position (the largest bubbles to the end). The outer loop repeats the passes (depends on number of elements).

Pass Array after the pass Note
start 10   5   6   3   7   8
1 5   6   3   7   8   10 10 bubbled to the end (5 swaps)
2 5   3   6   7   8   10 1 swap (6 ↔ 3)
3 3   5   6   7   8   10 1 swap (5 ↔ 3)
4 3   5   6   7   8   10 no swaps → NoSwaps = TRUE → stop

green = already in its final position · the efficient version stops after pass 4; the inefficient one would keep looping.

Inefficient

Two FOR loops — performs extra unwanted loops even if already sorted.

FOR X ← 1 TO 10 FOR Y ← 1 TO 9 IF arrayData[Y] > arrayData[Y+1] THEN temp ← arrayData[Y] arrayData[Y] ← arrayData[Y+1] arrayData[Y+1] ← temp ENDIF ENDFOR ENDFOR

Efficient

Outer loop = conditional loop with a flag; inner loop = FOR loop. Boundary shrinks each pass.

questionarray studentID of 10 elements — bubble sort, ascending
Boundary ← 9 REPEAT NoSwaps ← TRUE FOR J ← 1 TO Boundary IF studentID[J] > studentID[J + 1] THEN Temp ← studentID[J] studentID[J] ← studentID[J + 1] studentID[J + 1] ← Temp NoSwaps ← FALSE ENDIF ENDFOR Boundary ← Boundary − 1 UNTIL NoSwaps = TRUE

Boundary = number of elements − 1 (for 10 elements start at 9). The board example used Boundary = 4, i.e. a 5-element array — adjust to the question. For a descending sort change > to <.

✓ Quick Recap — Part C
  • Use ←, DECLARE every variable, indent, capitalise keywords · "&" joins strings · PRINT needs brackets + quotes
  • IF…THEN…ELSEIF…ELSE…ENDIF · CASE…OF…OTHERWISE…ENDCASE · AND = both, OR = either
  • LENGTH · LEFT · RIGHT · MID(s, start, n) · INT · ASC/CHR · ISNUM · STR_TO_NUM / NUM_TO_STR
  • FOR (known count) · WHILE (check first, may run 0 times) · REPEAT…UNTIL (runs at least once)
  • Sum, count, largest, smallest: initialise outside loop · flag looping for "until correct"
  • 1D: ARRAY[LB:UB] OF TYPE · 2D: ARRAY[rows, cols] with nested loops (rows outer, columns inner)
  • Files: OPENFILE … FOR READ/WRITE/APPEND · READFILE / WRITEFILE · CLOSEFILE · WHILE NOT EOF()
  • FUNCTION … RETURNS … RETURN · PROCEDURE … CALL · BYVAL (copy) / BYREF (original changes)
  • Bubble sort: swap with temp; flag NoSwaps + shrinking Boundary = efficient