πŸ“˜ O-Level Computer Science Β· Paper 2

Pseudocode Complete Notes

Everything you need β€” data types, loops, arrays, functions, files, SQL and full worked examples. Built for Cambridge O-Level CS.

01 Data Types & Variables β–Ύ

Every piece of data stored in a program has a type. Choosing the right type matters β€” it tells the computer how much memory to use and what operations are allowed.

INTEGER
Whole numbers only. No decimals.
55, 23, -8, 0, 105
STRING
Any text inside speech marks.
"Ali", "35", "TRUE", "Q"
REAL
Decimal / floating-point numbers.
23.4, 3.142, 55.0
BOOLEAN
Only two possible values.
TRUE, FALSE
CHAR
A single character in single quotes.
'a', 'M', '?', '1'
⚠️
Common trap: "35" is a STRING, not an integer β€” the speech marks make it text. You cannot do maths on it without converting it first.
Declaring Variables

Use DECLARE to tell the program a variable exists before using it.

Pseudocode
DECLARE colour : STRING
DECLARE age    : INTEGER
DECLARE price  : REAL
DECLARE flag   : BOOLEAN
DECLARE grade  : CHAR
Assigning Values

Use the arrow ← to assign a value to a variable (read it as "gets" or "is set to").

Pseudocode
colour      ← "red"
age         ← 18
price       ← 9.99
flag        ← FALSE
grade       ← 'A'

CONST pi   ← 3.1415   // constant β€” cannot be changed later
pi          ← 3.142    // βœ— ERROR β€” cannot reassign a constant
INPUT and OUTPUT
Pseudocode
OUTPUT "Enter your name"     // shows a message on screen
INPUT  name                  // waits for user to type something
OUTPUT "Hello, ", name       // outputs text + variable together
02 Operators & Expressions β–Ύ
OperatorMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division (real result)7 / 23.5
MODRemainder after division7 MOD 21
DIVInteger division (no decimal)7 DIV 23
=Equal tox = 5TRUE/FALSE
<>Not equal tox <> 5TRUE/FALSE
> < >= <=Comparison operatorsage >= 18TRUE/FALSE
ANDBoth conditions must be TRUEx > 0 AND x < 10TRUE/FALSE
ORAt least one must be TRUEx = 0 OR x = 1TRUE/FALSE
NOTInverts TRUE/FALSENOT flagTRUE/FALSE
&String concatenation"Hi " & name"Hi Ali"
πŸ’‘
MOD trick: To check if a number is even, use num MOD 2 = 0. To check divisibility by any number n, use num MOD n = 0.
03 IF / ELSE Statements β–Ύ
Basic Structure
Pseudocode
IF age >= 18 THEN
    OUTPUT "Eligible to vote"
ELSE
    OUTPUT "Not eligible"
ENDIF
Nested IF (ELSE IF)
Pseudocode
IF hours > 50 THEN
    OUTPUT "Overtime Bonus"
ELSE IF hours > 30 AND hours <= 50 THEN
    OUTPUT "Normal Salary"
ELSE
    OUTPUT "Salary Deducted"
ENDIF
⚠️
Always end with ENDIF. A very common exam mistake is writing END IF as two words β€” it must be one word.
Practice Questions
Q1 Take temperature as input. Output "Too Hot" if > 40, else "Pleasant weather".
Solution
OUTPUT "Enter temperature"
INPUT  temperature
IF temperature > 40 THEN
    OUTPUT "Too Hot"
ELSE
    OUTPUT "Pleasant weather"
ENDIF
Q2 Take 2 numbers. If num1 is greater output num1 Γ— 3. If num2 is greater output num2 Γ— 5. If equal, output num1 + num2.
Solution
OUTPUT "Enter first number"
INPUT  num1
OUTPUT "Enter second number"
INPUT  num2

IF num1 > num2 THEN
    OUTPUT num1 * 3
ELSE IF num2 > num1 THEN
    OUTPUT num2 * 5
ELSE
    OUTPUT num1 + num2
ENDIF
04 CASE OF Statement β–Ύ

Use CASE OF when you have one variable that can match many specific values. It is cleaner than writing lots of ELSE IF chains.

General Structure
CASE OF variable
    value1 : OUTPUT "..."
    value2 : OUTPUT "..."
    value3 : OUTPUT "..."
OTHERWISE :
    OUTPUT "Invalid input"
ENDCASE
Example β€” Simple Calculator
Pseudocode
OUTPUT "Enter two numbers"
INPUT  num1, num2
OUTPUT "Enter operator (+, -, *, /)"
INPUT  operator

CASE OF operator
    '+' : OUTPUT num1 + num2
    '-' : OUTPUT num1 - num2
    '*' : OUTPUT num1 * num2
    '/' : OUTPUT num1 / num2
OTHERWISE :
    OUTPUT "Invalid operator"
ENDCASE
Example β€” Grade to Points
Pseudocode
OUTPUT "Enter grade (A/B/C/D/F)"
INPUT  grade

CASE OF grade
    'A' : OUTPUT "Grade A β€” 4.0 points"
    'B' : OUTPUT "Grade B β€” 3.0 points"
    'C' : OUTPUT "Grade C β€” 2.0 points"
    'D' : OUTPUT "Grade D β€” 1.0 points"
    'F' : OUTPUT "Grade F β€” 0.0 points"
OTHERWISE :
    OUTPUT "Invalid grade"
ENDCASE
05 FOR Loop (Count-Controlled) β–Ύ
πŸ“Œ
When to use it: Use a FOR loop when you know exactly how many times you want to repeat something before the loop starts.
General Structure
FOR index ← 1 TO 10
    // code repeated 10 times
NEXT index

// Counting down using STEP
FOR index ← 10 TO 1 STEP -1
    OUTPUT index
NEXT index

// Even numbers only using STEP 2
FOR index ← 2 TO 20 STEP 2
    OUTPUT index
NEXT index
Practice β€” Sum & Average of 20 Numbers
Pseudocode
sum ← 0
FOR index ← 1 TO 20
    OUTPUT "Enter a number"
    INPUT  num
    sum ← sum + num
NEXT index
OUTPUT "Sum: ", sum
OUTPUT "Average: ", sum / 20
Practice β€” Temperature Monitor (7 Days)
Pseudocode
hotDays  ← 0
niceDays ← 0
coldDays ← 0

FOR index ← 1 TO 7
    OUTPUT "Enter temperature for day ", index
    INPUT  temp
    IF temp > 30 THEN
        OUTPUT "Hot day"
        hotDays ← hotDays + 1
    ELSE IF temp >= 20 AND temp <= 30 THEN
        OUTPUT "Nice day"
        niceDays ← niceDays + 1
    ELSE
        OUTPUT "Cold day"
        coldDays ← coldDays + 1
    ENDIF
NEXT index

OUTPUT "Hot days:  ", hotDays
OUTPUT "Nice days: ", niceDays
OUTPUT "Cold days: ", coldDays
06 WHILE Loop (Pre-Condition) β–Ύ
πŸ“Œ
When to use it: Use WHILE when you don't know how many times to loop. The condition is checked before entering the loop β€” so if it starts FALSE, the loop body never runs.
General Structure
index ← 1
WHILE index <= 10
    OUTPUT index
    index ← index + 1
ENDWHILE
Example β€” Sum Until User Enters 0
Pseudocode
sum ← 0
OUTPUT "Enter a number (0 to stop)"
INPUT  num
WHILE num <> 0
    sum ← sum + num
    OUTPUT "Enter a number (0 to stop)"
    INPUT  num
ENDWHILE
OUTPUT "Total: ", sum
Example β€” Password Login System (3 Attempts)
Pseudocode
flag  ← FALSE
tries ← 3

WHILE flag = FALSE AND tries > 0
    OUTPUT "Attempts remaining: ", tries
    OUTPUT "Enter password"
    INPUT  password
    IF password = "hello123" THEN
        flag ← TRUE
    ENDIF
    tries ← tries - 1
ENDWHILE

IF flag = TRUE THEN
    OUTPUT "Access Granted"
ELSE
    OUTPUT "Access Denied"
ENDIF
Example β€” Factorial (5! = 120)
Pseudocode
OUTPUT "Enter a number"
INPUT  num
index     ← 1
factorial ← 1
WHILE index <= num
    factorial ← factorial * index
    index     ← index + 1
ENDWHILE
OUTPUT "Factorial: ", factorial
07 REPEAT UNTIL Loop (Post-Condition) β–Ύ
πŸ“Œ
Key difference: REPEAT UNTIL always runs at least once because the condition is checked after the code runs. Perfect for input validation.

WHILE pre-condition

Checks condition BEFORE running. May never run if condition starts FALSE.

REPEAT UNTIL post-condition

Checks condition AFTER running. Always runs at least once. Loops UNTIL condition is TRUE.

Input Validation
Pseudocode
// Keeps asking until user enters a number between 1 and 12
REPEAT
    OUTPUT "Enter month (1-12)"
    INPUT  month
UNTIL month >= 1 AND month <= 12
Example β€” Even and Odd Sum (1 to 10)
Pseudocode
oddSum  ← 0
evenSum ← 0
index   ← 1
REPEAT
    IF index MOD 2 = 0 THEN
        evenSum ← evenSum + index
    ELSE
        oddSum  ← oddSum  + index
    ENDIF
    index ← index + 1
UNTIL index > 10
OUTPUT "Even sum: ", evenSum
OUTPUT "Odd sum:  ", oddSum
08 1D Arrays β–Ύ

An array is a collection of values of the same data type, stored under one name and accessed by an index number.

Declaring, Assigning & Accessing
Pseudocode
// Declare β€” 10 integers, indexed 1 to 10
DECLARE Scores : ARRAY[1:10] OF INTEGER

// Assign directly
Scores[1] ← 85
Scores[2] ← 92

// Initialise all elements to 0 using a loop
FOR index ← 1 TO 10
    Scores[index] ← 0
NEXT index

// Take input from user
FOR index ← 1 TO 10
    OUTPUT "Enter score"
    INPUT  Scores[index]
NEXT index
Linear Search (Efficient Version)
Pseudocode
FUNCTION LinearSearch(ValToFind : INTEGER) RETURNS BOOLEAN
    exit  ← FALSE
    index ← 1
    REPEAT
        IF ValToFind = Scores[index] THEN
            exit ← TRUE
        ELSE
            index ← index + 1
        ENDIF
    UNTIL index > 10 OR exit = TRUE
    RETURN exit
ENDFUNCTION
πŸ’‘
The efficient version stops as soon as it finds the value using exit ← TRUE β€” it doesn't keep checking the rest of the array unnecessarily.
Example β€” Find Largest Number
Pseudocode
DECLARE Values : ARRAY[1:5] OF INTEGER

FOR index ← 1 TO 5
    OUTPUT "Enter a value"
    INPUT  Values[index]
NEXT index

largest ← Values[1]   // start with first element
FOR index ← 2 TO 5
    IF Values[index] > largest THEN
        largest ← Values[index]
    ENDIF
NEXT index
OUTPUT "Largest value: ", largest
Example β€” Bubble Sort (Efficient)
Pseudocode
// Sorts Scores[1:10] in ascending order
upperBound ← 10
REPEAT
    upperBound ← upperBound - 1
    swap       ← FALSE
    FOR index ← 1 TO upperBound
        IF Scores[index] > Scores[index+1] THEN
            temp               ← Scores[index]
            Scores[index]     ← Scores[index+1]
            Scores[index+1]   ← temp
            swap               ← TRUE
        ENDIF
    NEXT index
UNTIL upperBound = 0 OR swap = FALSE   // stop early if already sorted
09 2D Arrays β–Ύ

A 2D array is like a table with rows and columns. Think of it as a grid. You need two index numbers to access any one cell: Array[row, col].

Declaring & Accessing
Pseudocode
// 5 students, 3 columns (e.g. score in 3 subjects)
DECLARE Marks : ARRAY[1:5, 1:3] OF INTEGER

Marks[1,1] ← 85   // student 1, subject 1
Marks[2,3] ← 70   // student 2, subject 3
Input & Output with Nested Loops
Pseudocode
// Taking input
FOR rows ← 1 TO 5
    FOR cols ← 1 TO 3
        OUTPUT "Enter mark for student ", rows, " subject ", cols
        INPUT  Marks[rows, cols]
    NEXT cols
NEXT rows

// Outputting values
FOR rows ← 1 TO 5
    FOR cols ← 1 TO 3
        OUTPUT Marks[rows, cols]
    NEXT cols
NEXT rows
Linear Search in 2D Array (Efficient)
Pseudocode
OUTPUT "Enter value to find"
INPUT  ValToFind
rows ← 1
exit ← FALSE
REPEAT
    cols ← 1
    REPEAT
        IF Marks[rows, cols] = ValToFind THEN
            exit ← TRUE
        ELSE
            cols ← cols + 1
        ENDIF
    UNTIL cols > 3 OR exit = TRUE
    rows ← rows + 1
UNTIL rows > 5 OR exit = TRUE

IF exit = TRUE THEN
    OUTPUT "Value found at row ", rows-1, " col ", cols
ELSE
    OUTPUT "Value not found"
ENDIF
StudentData β€” Search by ID, Output Name
Pseudocode β€” StudentData[1:1000, 1:2] col1=ID col2=Name
OUTPUT "Enter the student ID"
INPUT  Id
found ← FALSE
rows  ← 1
REPEAT
    IF StudentData[rows, 1] = Id THEN
        found ← TRUE
    ELSE
        rows ← rows + 1
    ENDIF
UNTIL rows > 1000 OR found = TRUE

IF found = TRUE THEN
    OUTPUT "Name: ", StudentData[rows, 2]
ELSE
    OUTPUT "ID not found"
ENDIF
10 Functions & Procedures β–Ύ

FUNCTION returns a value

Takes parameters, does something, and returns a result you can store in a variable.

PROCEDURE no return value

Takes parameters and does something (e.g. outputs to screen), but returns nothing.

FUNCTION β€” Grade Calculator
Pseudocode
FUNCTION GradeCalc(m1:INTEGER, m2:INTEGER, m3:INTEGER) RETURNS CHAR
    total      ← m1 + m2 + m3
    percentage ← total / 3
    OUTPUT "Total: ", total, "  Percentage: ", percentage

    CASE OF percentage
        >= 90 : grade ← 'A'
        >= 80 : grade ← 'B'
        >= 70 : grade ← 'C'
        >= 60 : grade ← 'D'
    OTHERWISE : grade ← 'F'
    ENDCASE
    RETURN grade
ENDFUNCTION

// Calling the function
OUTPUT "Enter marks for 3 subjects"
INPUT  s1, s2, s3
result ← GradeCalc(s1, s2, s3)
OUTPUT "Your grade is: ", result
PROCEDURE β€” Draw Triangle of Stars
Pseudocode
PROCEDURE DrawTriangle(size : INTEGER)
    FOR rows ← 1 TO size
        FOR col ← 1 TO rows
            OUTPUT "*"
        NEXT col
        OUTPUT ""   // new line
    NEXT rows
ENDPROCEDURE

// Calling the procedure
DrawTriangle(5)   // prints a 5-row triangle
11 File Handling β–Ύ

Files let you store data permanently. Without files, all data is lost when the program ends. There are two modes: READ and WRITE.

⚠️
Always OPENFILE before reading/writing, and always CLOSEFILE when done. Forgetting CLOSEFILE is a common exam error.
Writing to a File
Pseudocode
OPENFILE "data.txt" FOR WRITE
WRITEFILE "data.txt", "This is line one"
WRITEFILE "data.txt", "This is line two"
CLOSEFILE "data.txt"
Reading from a File (Until End of File)
Pseudocode
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt")
    READFILE "data.txt", oneLine
    OUTPUT   oneLine
ENDWHILE
CLOSEFILE "data.txt"
Example β€” Split Scores into High / Medium / Low Files
Pseudocode
OPENFILE "exam_scores.txt" FOR READ
OPENFILE "high.txt"        FOR WRITE
OPENFILE "medium.txt"      FOR WRITE
OPENFILE "low.txt"         FOR WRITE

WHILE NOT EOF("exam_scores.txt")
    READFILE "exam_scores.txt", score
    IF score >= 80 THEN
        WRITEFILE "high.txt", score
    ELSE IF score >= 50 THEN
        WRITEFILE "medium.txt", score
    ELSE
        WRITEFILE "low.txt", score
    ENDIF
ENDWHILE

CLOSEFILE "exam_scores.txt"
CLOSEFILE "high.txt"
CLOSEFILE "medium.txt"
CLOSEFILE "low.txt"
12 SQL β€” Database Queries β–Ύ

SQL (Structured Query Language) is used to retrieve data from a database table. In your exam you need to know four keywords.

KeywordWhat it doesRequired?
SELECTChoose which columns (fields) to display. Use * to select all.βœ… Always
FROMWhich table to query.βœ… Always
WHEREFilter rows based on a condition.Optional
ORDER BYSort results. Add ASC (low→high) or DESC (high→low).Optional
Examples
SQL β€” Table: STUDENT (StudentID, FirstName, LastName, YearGroup, Score, Grade)
-- Show all data
SELECT * FROM STUDENT

-- Show names of all Year 11 students scoring above 70, highest score first
SELECT FirstName, LastName, Score
FROM   STUDENT
WHERE  YearGroup = 11 AND Score > 70
ORDER BY Score DESC

-- Show all students in House 'Blue', sorted by name A-Z
SELECT FirstName, LastName
FROM   STUDENT
WHERE  HouseColour = 'Blue'
ORDER BY LastName ASC

-- Show all Grade A students
SELECT *
FROM   STUDENT
WHERE  Grade = 'A'
πŸ“
Exam tip: Text values like 'Blue' go in single quotes. Numbers like 70 do not. Getting this wrong is an easy mark to lose.
13 Worked 15-Mark Exam Questions β–Ύ
🎯
How to approach 15-mark questions: Read the requirements as a checklist. Write comments in your code for each requirement. Cover validation, loops, arrays, and output with meaningful messages.
Question 1 β€” Cricket League Points System

12 clubs. Track wins/draws/losses. Calculate points (Win=12, Draw=5, Loss=0). Find the club(s) with most points.

Full Solution
// Step 1: Input and validate number of matches (max 22)
REPEAT
    OUTPUT "Enter number of matches played (max 22)"
    INPUT  Matches
UNTIL Matches >= 1 AND Matches <= 22

// Step 2: Input club names and match results
FOR index ← 1 TO 12
    OUTPUT "Enter name of club ", index
    INPUT  Clubs[index]

    // Validate: wins + draws + losses must equal Matches
    REPEAT
        OUTPUT "Enter matches won"
        INPUT  won
        OUTPUT "Enter matches drawn"
        INPUT  drawn
        OUTPUT "Enter matches lost"
        INPUT  lost
        IF (won + drawn + lost) <> Matches THEN
            OUTPUT "Error: totals must add up to ", Matches
        ENDIF
    UNTIL (won + drawn + lost) = Matches

    Statistics[index, 1] ← won
    Statistics[index, 2] ← drawn
    Statistics[index, 3] ← lost

    // Step 3: Calculate points
    Points[index] ← (won * 12) + (drawn * 5)
NEXT index

// Step 4: Find the highest points total
highest ← -1
FOR index ← 1 TO 12
    IF Points[index] > highest THEN
        highest ← Points[index]
    ENDIF
NEXT index

// Step 5: Find and output all clubs with the highest points
DECLARE topTeams : ARRAY[1:12] OF INTEGER
count ← 0
FOR index ← 1 TO 12
    IF Points[index] = highest THEN
        count          ← count + 1
        topTeams[count] ← index
    ENDIF
NEXT index

FOR index ← 1 TO count
    OUTPUT "Winner: ", Clubs[topTeams[index]]
    OUTPUT "Wins:   ", Statistics[topTeams[index], 1]
    OUTPUT "Points: ", highest
NEXT index
Question 2 β€” Grid Treasure Hunt Game

5Γ—5 grid. Place 'X' randomly (not at [1,1]). Player starts at [1,1]. 10 moves to find X using W/A/S/D.

Full Solution
// Step 1: Initialise grid with empty strings
FOR row ← 1 TO 5
    FOR col ← 1 TO 5
        Grid[row, col] ← ""
    NEXT col
NEXT row

// Step 2: Place 'X' in a random cell (not [1,1])
REPEAT
    Xrow ← ROUND(RANDOM() * 4, 0) + 1
    Xcol ← ROUND(RANDOM() * 4, 0) + 1
UNTIL Xrow <> 1 OR Xcol <> 1
Grid[Xrow, Xcol] ← 'X'

// Step 3: Initialise player position and move counter
PlayerRow ← 1
PlayerCol ← 1
moveCount ← 0
win       ← FALSE

// Step 4: Game loop β€” up to 10 moves
REPEAT
    OUTPUT "Position: [", PlayerRow, ",", PlayerCol, "]  Moves left: ", 10 - moveCount
    OUTPUT "W=Up  S=Down  A=Left  D=Right"
    INPUT  move
    move  ← UCASE(move)
    error ← FALSE
    tempR ← PlayerRow
    tempC ← PlayerCol

    CASE OF move
        'W' : tempR ← PlayerRow - 1
        'S' : tempR ← PlayerRow + 1
        'A' : tempC ← PlayerCol - 1
        'D' : tempC ← PlayerCol + 1
    OTHERWISE : error ← TRUE
    ENDCASE

    // Validate move is within grid bounds
    IF tempR < 1 OR tempR > 5 OR tempC < 1 OR tempC > 5 THEN
        error ← TRUE
        OUTPUT "Move out of bounds β€” try again"
    ENDIF

    IF error = FALSE THEN
        PlayerRow ← tempR
        PlayerCol ← tempC
        moveCount ← moveCount + 1
    ENDIF

    // Check win condition
    IF Grid[PlayerRow, PlayerCol] = 'X' THEN
        win ← TRUE
        OUTPUT "You Win! Found it in ", moveCount, " moves."
    ENDIF
UNTIL win = TRUE OR moveCount = 10

IF win = FALSE THEN
    OUTPUT "You Lose! The X was at [", Xrow, ",", Xcol, "]"
ENDIF
painlessprogramming.com β€” making the hardest CS concepts click πŸš€
Scroll to Top