Module 1
Syntax & Data Types
Cambridge non-negotiable conventions: keywords, identifiers, the six data types, DECLARE/CONSTANT, the <- arrow, literals and all operators.
A hospital's patient record stores: the patient's full name, their date of birth, their weight in kilograms (to 1 decimal place), their blood type as a single letter, and whether they are an organ donor. Write pseudocode to DECLARE these five variables with the most appropriate Cambridge data types.
A physics simulator uses the gravitational acceleration constant 9.81 m/s^2. The current velocity (REAL) of a falling object is then computed and stored. Write pseudocode to declare the gravitational constant using CONSTANT syntax, then declare a REAL variable Velocity and assign it the value 0.0 using the Cambridge assignment arrow.
A student has written the following pseudocode with incorrect keyword casing and no indentation. Rewrite the snippet using correct Cambridge conventions: ALL keywords in UPPER CASE and consistent four-space indentation inside each control structure.
declare age : integer
input age
if age >= 18 then
output "Adult"
else
output "Minor"
endifA library system needs variables for: the number of books on loan, the maximum books a member can borrow, the name of the current member, and whether the member has any overdue items. Using Cambridge mixed-case identifier conventions (camelCase or PascalCase, no underscores, no hyphens), write DECLARE statements for these four variables with the most appropriate data types.
A vending machine stores the product code (a single letter such as 'A'), the product name, the price in pounds (with pence), and whether the product is currently in stock. Write four assignment statements using correctly typed literals for the variables ProductCode : CHAR, ProductName : STRING, Price : REAL, and InStock : BOOLEAN.
A cinema sells tickets in batches. A batch contains a known number of tickets; any remainder after batching is sold individually at the door. Write pseudocode to input a total number of tickets sold (INTEGER), and output how many full batches were sold and how many individual tickets remained, assuming each batch holds 12 tickets. Use DIV and MOD.
A theme park ride admits a visitor only when ALL of the following are true: the visitor is at least 120 cm tall, the visitor is at most 16 years old, and the visitor is NOT accompanied by an adult who has paid for a VIP fast-pass. Given the variables Height : INTEGER, Age : INTEGER, and HasFastPass : BOOLEAN already declared and assigned, write a single BOOLEAN expression that evaluates to TRUE when the visitor is admitted. Do NOT use IF; just write the expression assigned to a BOOLEAN variable AllowEntry.
A driving licence expires 50 years after the holder's date of birth. Given a variable DateOfBirth : DATE that has already been declared and assigned, write pseudocode to declare ExpiryDate : DATE and assign it a value demonstrating the convention that Cambridge DATE arithmetic can add a number of years. Then OUTPUT the expiry date.
A student wrote the following buggy temperature-monitoring snippet for a freezer alarm. Rewrite it using Cambridge conventions (UPPER CASE keywords, four-space indentation) AND fix the assignment symbol so that all three threshold comparisons store their result in BOOLEAN variables.
declare temp : real
input temp
freeze = temp <= -18
warn = temp > -18 and temp <= 0
safe = temp > 0
output freeze, warn, safeA school information system stores a single student's record with the following fields: their unique 4-digit student ID (e.g. 0427), their full name, their form tutor's initial (a single letter), their average grade as a percentage to 2 decimal places, the date they enrolled, and whether they have paid the optional trip deposit. Write pseudocode to DECLARE all six variables with the most appropriate Cambridge data type. Justify in a comment why StudentID is a STRING despite looking like a number.
A water tank is shaped like a cube with side length Side (INTEGER cm). The tank is filled with water to a depth of DepthCm (INTEGER cm). Write pseudocode to: (1) declare Side and DepthCm as INTEGER, (2) declare Volume (REAL) and WaterVolume (REAL), (3) compute the total tank volume using the ^ operator, and (4) compute the water volume as Side * Side * DepthCm. Finally output both volumes.
A bank approves a customer for a loan when ALL the following hold: the customer is aged 21 or over; the customer's annual income is at least 25000; the customer is NOT currently bankrupt; AND EITHER the customer owns a property OR the customer has a guarantor. Given Age : INTEGER, Income : REAL, IsBankrupt : BOOLEAN, OwnsProperty : BOOLEAN, HasGuarantor : BOOLEAN (all already declared and assigned), write a single BOOLEAN expression assigned to Approve : BOOLEAN.
A bank pays a fixed annual interest rate of 5%. A customer deposits Principal (REAL pounds) for exactly 3 years (no withdrawals). Using a CONSTANT named RATE = 1.05 (the growth factor), write pseudocode to declare Principal (REAL) and FinalAmount (REAL), input Principal, compute FinalAmount = Principal * (RATE ^ 3), and output the result to 2 decimal places using ROUND.
A weather station records the following readings for one observation: the station's three-letter code (e.g. 'LHR'), the wind direction as a single character (e.g. 'N'), the temperature in Celsius (REAL), the barometric pressure in hPa (INTEGER), whether it is raining, and the timestamp as a DATE. Write pseudocode to DECLARE all six variables using clear mixed-case identifiers, then assign each a correctly-typed literal value of your choice.
A leap year in the Gregorian calendar is divisible by 4, EXCEPT for end-of-century years which must be divisible by 400. Given Year : INTEGER already declared and assigned, write a single BOOLEAN expression assigned to IsLeap : BOOLEAN that evaluates to TRUE when Year is a leap year. Use DIV, MOD, AND, OR, NOT and brackets as needed.
A spelling app needs to test whether a single character stored in Letter : CHAR is a vowel (upper or lower case). Write pseudocode to declare IsVowel : BOOLEAN and assign it TRUE when Letter is one of A, E, I, O, U (in either case). Use only relational operators (=), logical OR, and the UCASE function. Do NOT use IF.
Three side lengths A, B, C (all REAL) form a valid triangle only when the sum of any two sides is greater than the third. Given A, B and C already declared and assigned, write pseudocode to declare IsValid : BOOLEAN and assign it the result of the triangle inequality test using three relational conditions joined by AND.
A marathon timer records TotalSeconds (INTEGER). Write pseudocode to input TotalSeconds and output the equivalent time in HH:MM:SS form, where HH is the number of whole hours, MM is the remaining whole minutes (00-59) and SS is the remaining whole seconds (00-59). Use only DIV, MOD, INTEGER variables and string concatenation (&).
A quadratic equation ax^2 + bx + c = 0 (coefficients a, b, c all REAL, a <> 0) has a discriminant D = b^2 - 4ac. Write pseudocode to: input a, b, c; compute D; then output "Two real roots" when D > 0, "One repeated root" when D = 0, and "No real roots" when D < 0. Provide TWO valid approaches — one using nested IF/ELSE, one using an ELSEIF chain.
An electricity company charges a fixed daily standing charge of 0.40 pounds and 0.18 pounds per kWh used. The bill is reduced by 5% if usage is 200 kWh or less; otherwise a 2% surcharge applies. Write pseudocode to: declare CONSTANT STANDING = 0.40 and CONSTANT RATE = 0.18, declare Usage (REAL) and Bill (REAL), input Usage, then compute and output the final bill rounded to 2 decimal places. Provide TWO valid approaches — one using IF/ELSE, one using a CASE OF structure on a discount code.
Module 2
Control Flow — Selection & Iteration
The engine of pseudocode: IF/ELSE, ELSEIF, CASE OF, FOR, WHILE and REPEAT — the six constructs that drive every algorithm.
A teacher awards a PASS when a student's exam score is 50 or above; otherwise the student FAILS. Write pseudocode to input Score (INTEGER) and output either "PASS" or "FAIL" using a single IF/ELSE.
A primary school classroom displays the 5 times table on the board. Write pseudocode using a FOR loop to output the 5 times table from 5 x 1 up to 5 x 12.
A college assigns letter grades from a percentage score: A for 80-100, B for 70-79, C for 60-69, D for 50-59, F for 0-49. Write pseudocode to input Score (INTEGER, 0-100) and output the grade letter using an ELSEIF chain.
A scheduling app receives a DayNum (INTEGER 1-7). Write pseudocode using CASE OF to output the corresponding weekday name (1 = Monday ... 7 = Sunday) and use OTHERWISE to handle invalid inputs by outputting "Invalid day".
A rocket launch system counts down from 10 to 1, outputting each number, before outputting "LIFT OFF!". Write pseudocode using a WHILE loop (not FOR) and a Counter variable that starts at 10 and decreases by 1 each iteration.
A quiz application asks the user to enter their age (INTEGER), but the user must be aged between 5 and 120 inclusive. Write pseudocode using a REPEAT...UNTIL loop that keeps prompting until a valid age is entered. After the loop, output "Age accepted".
A countdown timer displays every even number from 20 down to 2 (i.e. 20, 18, 16, ..., 2). Write pseudocode using a single FOR loop with a NEGATIVE STEP value.
A calendar app must report whether a Year (INTEGER) is a leap year. Write pseudocode using NESTED IF statements (no compound AND/OR): if Year is divisible by 4, check if it is divisible by 100; if so, also check if divisible by 400. Output "Leap year" or "Not a leap year".
A text-based calculator repeatedly shows a menu (1 = Add, 2 = Subtract, 3 = Quit) until the user picks 3. Write pseudocode using a WHILE loop that handles one of the two arithmetic options on each pass. Display the menu, INPUT Choice, and use IF/ELSEIF inside the loop. Quit cleanly when Choice = 3.
A maths drill asks students to compute the sum 1^2 + 2^2 + ... + 10^2 using pseudocode. Write pseudocode that uses an accumulator Sum (INTEGER) initialised to 0 and a FOR loop from 1 to 10. Output the final sum.
A simple calculator inputs two REAL numbers (Num1, Num2) and an operator character Op (CHAR: +, -, *, /). Use CASE OF to perform the selected operation and output the result. Use OTHERWISE for an invalid operator and include a guard inside the "/" case so that division by zero outputs "Cannot divide by zero" rather than crashing.
A simplified income tax system levies: 0% on the first 12500 pounds; 20% on the portion from 12501 to 50000; 40% on the portion from 50001 to 150000; 45% on the portion above 150000. Write pseudocode to input Salary (REAL) and output the total tax due, rounded to 2 decimals. Use an ELSEIF chain to choose the formula for each band.
A teacher enters a class of students' test scores one at a time. A score of -1 indicates the end of input (the sentinel — do not include it in the total). Write pseudocode using a WHILE loop to read scores, accumulate the total, count how many were entered, and finally output the average to 2 decimals. Guard against dividing by zero if no scores were entered.
A new account system requires a username that is between 5 and 15 characters in length (use the LENGTH function) AND does not contain spaces. The user keeps re-entering the username until both conditions hold. Write pseudocode using a REPEAT...UNTIL loop. After acceptance, output "Username accepted".
A classroom display prints a 12x12 multiplication table. Write pseudocode using two NESTED FOR loops (outer loop = row 1..12, inner loop = column 1..12) that outputs the product Row * Column for each cell, separated by a tab character "\t". Output a newline after each row.
A children's counting game prints numbers from 1 to 30 with the following twist: for multiples of 3 output "Fizz" instead of the number; for multiples of 5 output "Buzz"; for multiples of both 3 AND 5 output "FizzBuzz". Otherwise output the number itself. Write pseudocode using a FOR loop and a chain of IF/ELSEIF inside.
A loyalty programme assigns a tier from a Points value (INTEGER): 0-99 = Bronze, 100-499 = Silver, 500-999 = Gold, 1000+ = Platinum. Negative points are invalid. Because Cambridge CASE OF cannot range-test, derive a CategoryCode (INTEGER 1-5) using IF/ELSEIF, then use CASE OF to print the tier. Use OTHERWISE to handle the invalid case.
A teacher knows there are exactly 25 students in a class. Using a WHILE loop with a Counter from 1 to 25, input each student's mark (INTEGER 0-100), accumulate the total, and at the end output the class average to 2 decimal places. Use REAL for the average.
A number N (INTEGER >= 2) is prime if it has no whole-number divisor other than 1 and itself. Write pseudocode to input N and output "Prime" or "Not prime". Provide TWO valid approaches — one using a FOR loop with a Boolean flag (checks every divisor from 2 to N-1), and one using a WHILE loop with EARLY EXIT (stops as soon as a divisor is found).
A vending machine must return change of C pence (INTEGER) using the fewest coins. Available denominations: 50p, 20p, 10p, 5p, 2p, 1p. Write pseudocode to input C and output how many of EACH coin to dispense. Provide TWO valid approaches — one using a WHILE loop that subtracts each denomination in turn (greedy), and one using DIV and MOD to compute the counts arithmetically.
Module 3
Working with Data — Arrays, Files & Subprograms
Where most AS Level marks live: 1D/2D arrays, traversal/search/sort, file I/O, procedures, functions and BYVAL/BYREF parameters.
A school stores the names of 30 students in a class. Write pseudocode to DECLARE a 1D array ClassList that uses indices 1 to 30 and holds STRING values.
A cinema has 8 rows (numbered 1 to 8) with 12 seats per row (numbered 1 to 12). Each seat stores "E" if empty or "O" if occupied. Write pseudocode to DECLARE a 2D array Seats with the appropriate dimensions and element type.
A greeting utility needs a PROCEDURE called Welcome that takes no parameters and outputs "Welcome to the system!". Write pseudocode to define the procedure and then CALL it from the main program.
A teacher wants to input the marks of 5 students into a 1D array Marks (INTEGER, indices 1..5), then output each mark on its own line. Write pseudocode using two separate FOR loops — one for input, one for output.
A weather station records the daily temperature for 7 days across 4 weeks. Declare a 2D array Temps[1:4, 1:7] OF REAL. Use nested FOR loops to input every temperature, then use a second pair of nested FOR loops to output each week's temperatures on one line.
A geometry helper needs a function that takes the side length of a square (REAL) and RETURNS its area. Write pseudocode to define a FUNCTION SquareArea that takes one REAL parameter, computes side^2, and RETURNS the result. Then declare Side (REAL), input it, call SquareArea, and output the result.
A billing system has a PROCEDURE PrintReceipt that takes the total amount (REAL) BYVAL and outputs a formatted receipt. Write pseudocode to define PrintReceipt, then declare Total : REAL, input it, and CALL PrintReceipt passing Total. After the CALL, output Total again to confirm BYVAL did NOT modify the original.
A sorting routine needs a PROCEDURE Swap that exchanges the values of two INTEGER variables using BYREF parameters. Write pseudocode to define Swap(X : INTEGER BYREF, Y : INTEGER BYREF), then declare A and B, input them, CALL Swap(A, B), and output them to confirm the values were exchanged.
A loyalty app stores 100 customer IDs (INTEGER) in a 1D array CustomerIDs[1:100]. Write pseudocode to input a Target ID, then perform a linear search to find the index of Target. Output the index if found, or "Not found" if Target is not in the array.
A teacher has 5 student marks in a 1D array Marks[1:5] OF INTEGER. Write pseudocode to perform ONE pass of bubble sort (compare each adjacent pair from index 1 to 4, swapping if out of order) and then output the array. Do NOT loop until sorted — just one pass.
A log file "sales.txt" contains an unknown number of sale amounts (REAL), one per line. Write pseudocode to OPENFILE for READ, then loop using WHILE NOT EOF("sales.txt") to READFILE each amount and OUTPUT it, and finally CLOSEFILE.
A registration system asks the user to input a new customer's name (STRING) and email (STRING), then APPENDs both as separate lines to an existing file "customers.txt". Write pseudocode to OPENFILE for APPEND, INPUT the two values, WRITEFILE each on its own line, then CLOSEFILE.
A weather station has 365 daily temperatures (REAL) in array Temps[1:365]. Write pseudocode to find BOTH the highest and the lowest temperatures in a SINGLE pass through the array (one FOR loop), and output them with labels.
A class of 30 students has INTEGER marks in array Marks[1:30]. Write pseudocode to compute the sum (INTEGER) and the average (REAL, to 2 decimal places). Output both. Ensure that integer division is avoided when computing the average.
A leaderboard stores 8 player scores (INTEGER) in Scores[1:8]. Write pseudocode to fully sort the array in DESCENDING order (highest first) using bubble sort with a Swapped flag so the algorithm exits early once the array is sorted. Output the sorted array.
A shop has 4 branches (rows 1-4) and 7 days of sales (columns 1-7) in a 2D array Sales[1:4, 1:7] OF INTEGER. Write pseudocode to compute and output the total sales for EACH branch (row total), and the total sales for EACH day (column total). Use two separate nested-FOR accumulations.
A library stores 500 book titles (STRING) in Books[1:500]. Write pseudocode to input a Target title and perform a linear search. If found, output the index. If not found, output -1. Use a Found flag and break out of the loop early once the target is found.
A statistics module needs a FUNCTION AverageOf that takes a 1D array of 20 INTEGER values and RETURNS the average as a REAL. Write the function definition, then declare an array Marks[1:20] OF INTEGER (assume populated), call AverageOf, and output the result to 2 decimals.
A data-cleaning routine has a PROCEDURE DoubleAll that takes a 1D array of 10 INTEGERs BYREF and doubles every element in place. Write pseudocode to define DoubleAll, then declare an array Nums[1:10] OF INTEGER (assume populated), CALL DoubleAll(Nums), and output the array to confirm each value was doubled.
A demonstration has TWO procedures: IncrementByVal(BYVAL N : INTEGER) which adds 1 to N inside (no effect on caller), and IncrementByRef(BYREF N : INTEGER) which adds 1 to N inside (affects caller). Write pseudocode to declare Counter : INTEGER = 0, call IncrementByVal(Counter) and output Counter (still 0), then call IncrementByRef(Counter) and output Counter (now 1).
A file "rainfall.txt" contains an unknown number of daily rainfall measurements (REAL, in mm). Write pseudocode to OPENFILE for READ, loop until EOF, READFILE each value, count the days, accumulate the total rainfall, and finally CLOSEFILE and output both count and total to 2 decimals.
A teacher has 25 student marks (INTEGER) in Marks[1:25]. Write pseudocode to OPENFILE "marks.txt" FOR WRITE, then use a FOR loop to WRITEFILE each mark on its own line, then CLOSEFILE. (Note: WRITE mode overwrites any existing file.)
A game leaderboard stores 50 players' names (STRING) in Names[1:50] and their scores (INTEGER) in Scores[1:50] (the parallel arrays are aligned by index). Write pseudocode to find the player with the highest score and output their name and score. Handle ties by outputting the first player who achieved that score.
A 4x4 matrix of INTEGERs is stored in Matrix[1:4, 1:4]. Write pseudocode to compute and output the sum of the MAIN diagonal (where row = column, i.e. Matrix[1,1] + Matrix[2,2] + Matrix[3,3] + Matrix[4,4]).
A theatre has 10 rows of 20 seats stored as SeatChart[1:10, 1:20] OF STRING where each cell is "E" (empty) or "O" (occupied). Write pseudocode to find the FIRST empty seat (scanning row by row, seat by seat from row 1 seat 1) and output its row and seat numbers. If no seat is empty, output "Sold out".
A data-validation module needs a FUNCTION IsSorted that takes a 1D array of 10 INTEGERs and RETURNS TRUE if the array is sorted in ASCENDING order (each element <= the next), FALSE otherwise. Write the function definition, then call it on an array Nums[1:10] and output "Sorted" or "Not sorted".
A reusable utility needs a PROCEDURE SortAscending that takes a 1D array of 6 INTEGERs BYREF and sorts it in ascending order using bubble sort. Write pseudocode to define SortAscending, then declare an array Nums[1:6] OF INTEGER (assume populated), CALL SortAscending(Nums), and output the sorted array.
A teacher has 30 marks (INTEGER, range 0-100) in Marks[1:30]. The teacher wants to count how many students scored each mark from 0 to 100. Provide TWO valid approaches — one using a frequency array Freq[0:100] indexed directly by the mark value, and one using two parallel arrays (UniqueMark[1:101] and Count[1:101]) with a linear search to find or insert each mark.
A file "nums.txt" contains up to 100 INTEGER values, one per line. Write pseudocode to read all values into an array, sort the array in ascending order, then write the sorted values back to the same file (overwriting it). Provide TWO valid approaches — one uses the SAME file for read and rewrite (close then reopen in WRITE mode); the other writes to a TEMPORARY file "sorted.txt" first, then could be renamed.
A cinema has 8 rows of 12 seats. Write pseudocode to declare a 2D array representing the seating, initialise every seat as available, then INPUT a row (1-8) and seat (1-12) and book that seat by marking it as occupied (output "Booked" or "Already taken"). Provide TWO valid approaches — one using a 2D array of STRING ("E"/"O"), one using a 2D array of BOOLEAN (TRUE = available).
Module 4
Strings & Built-in Functions
The Cambridge built-in toolkit: LENGTH, MID, RIGHT, UCASE/LCASE, & concatenation, plus INT(x) for truncation and RAND(x) for random integers.
A website form asks a user to type a tweet (STRING). The site limits tweets to 280 characters. Write pseudocode to input the tweet and OUTPUT its character count using the LENGTH built-in.
A login system stores a user's first name and last name in two separate STRING variables FirstName and LastName. Write pseudocode to declare a third STRING variable FullName and build it by joining FirstName, a single space, and LastName using the & operator. OUTPUT the result.
A 7-character product code is stored in Code (STRING). The middle three characters (positions 3, 4 and 5) identify the product category. Write pseudocode to extract those three characters into a STRING variable Category using the MID built-in, and OUTPUT the category. (Cambridge MID takes the start position and the number of characters.)
A bank stores a customer's 16-digit card number as a STRING in CardNumber. For security, only the last 4 digits should be displayed on receipts. Write pseudocode to extract the last 4 characters into a STRING variable LastFour using the RIGHT built-in and OUTPUT them.
A login form is case-insensitive for usernames: "Alice", "alice" and "ALICE" should all match the stored value "ALICE". Write pseudocode to INPUT a username (STRING), convert it to UPPER CASE using UCASE, and OUTPUT a welcome message showing the upper-cased username.
A shop prices items in dollars and cents but its receipt printer can only print whole-dollar amounts. Given Price : REAL already declared and assigned, write pseudocode to declare WholeDollars : INTEGER and use the INT built-in to truncate the price to a whole number. OUTPUT the result. (Note: INT truncates toward zero, so 9.99 becomes 9, not 10.)
A board game needs to simulate a fair six-sided die. Cambridge's RAND(x) returns a random INTEGER from 0 to x-1 inclusive. Write pseudocode to roll the die and OUTPUT a value from 1 to 6.
A phone number validator requires the user to enter exactly 10 digits. Write pseudocode to INPUT a phone number (STRING), check its length with LENGTH, and OUTPUT "Valid" if the length is 10 or "Invalid: must be 10 digits" otherwise.
A name is stored in Name (STRING) with words separated by single spaces. Every word starts with a lower-case letter. Write pseudocode to build a new string in which the first letter of EVERY word is converted to UPPER CASE, and OUTPUT it. (Hint: capitalise position 1, then any character that follows a space.)
A full name is stored as "FirstName MiddleName LastName" in FullName (STRING) — three words separated by single spaces. Write pseudocode to extract the first letter of each word and build a string of initials separated by full stops, e.g. "John Robert Smith" → "J.R.S.". OUTPUT the result.
A file-upload system accepts only text files with the extension ".txt" (case-insensitive — ".TXT", ".Txt" and ".txt" should all be accepted). Given FileName : STRING already declared and assigned, write pseudocode to extract the last 4 characters with RIGHT, convert them to UPPER CASE with UCASE, and OUTPUT "Accepted" if they equal ".TXT" or "Rejected" otherwise.
A palindrome is a word that reads the same forwards and backwards (e.g. "racecar"). Write pseudocode to INPUT a single word (STRING) and check whether it is a palindrome. OUTPUT "Palindrome" or "Not a palindrome". Use LENGTH and MID — do NOT reverse the string.
A teacher has computed a class average as a REAL value in Average (e.g. 73.6). Cambridge's INT truncates toward zero, so INT(73.6) = 73, not 74. Write pseudocode to declare Rounded : INTEGER and round Average to the nearest whole number using INT and arithmetic only (no ROUND built-in). OUTPUT the result. (Hint: add 0.5 before truncating.)
A lottery draws 6 unique numbers, each between 1 and 49 inclusive. Write pseudocode to fill an array Balls[1:6] of INTEGER with 6 unique random numbers (no repeats). OUTPUT each number on its own line. (Hint: before adding a new number, check it is not already in the array; if it is, draw again.)
A school assigns every student an email of the form: first initial + last name + "@school.edu" — all in LOWER CASE. Given FirstName and LastName (both STRING, already declared), write pseudocode to build Email and OUTPUT it. If LastName is longer than 10 characters, use only the first 10 characters of it (use MID).
A sentence is stored in Sentence (STRING). Write pseudocode to count how many vowels (A, E, I, O, U) it contains. Output the count. Use MID to extract each character, UCASE to handle both cases, and a CASE OF to test the character.
A Caesar cipher with a shift of 1 turns "ABC" into "BCD" (every letter is replaced by the next one in the alphabet; "Z" wraps to "A"). A plaintext message is stored in PlainText (STRING, UPPER CASE letters only). Write pseudocode to build CipherText by shifting each character one position forward and OUTPUT the result.
A stopwatch records the total seconds elapsed as an INTEGER in TotalSeconds. Write pseudocode to convert this into hours, minutes and seconds (three INTEGER outputs). Use INT, DIV and MOD. OUTPUT in the form "Hh Mm Ss" (e.g. "1h 5m 12s" for 3912 seconds).
A programmer stores variable names in snake_case (words separated by underscores, e.g. "user_first_name"). Write pseudocode to convert snake_case Snake (STRING) into camelCase and OUTPUT the result. Provide TWO valid approaches — Approach 1 scans character-by-character building the result; Approach 2 first removes underscores by replacing them with spaces, then capitalises the first letter of each word after the first.
Two players each roll a six-sided die three times. The player with the higher total wins; on a tie, output "Draw". Write pseudocode to play one round and OUTPUT the winner ("Player 1 wins", "Player 2 wins" or "Draw"). Provide TWO valid approaches — Approach 1 uses two parallel arrays Rolls1[1:3] and Rolls2[1:3] plus a FOR loop; Approach 2 uses scalar variables (Roll1_Total and Roll2_Total) and a REPEAT...UNTIL counter.
Module 5
Abstract Data Types (Conceptual)
AS Level theory in action: Stacks (LIFO), Queues (FIFO) and Linked Lists — explained, traced and implemented with arrays.
Explain what is meant by a Stack data structure, state what the acronym LIFO stands for, and give ONE real-world analogy for it.
An empty stack S supports the PUSH and POP operations. Show the contents of S (top on the right) after each of these operations: PUSH(S, 10), PUSH(S, 20), PUSH(S, 30). Then state which value POP(S) would return if called next.
An empty queue Q supports the ENQUEUE and DEQUEUE operations. Show the contents of Q (front on the left) after each of these operations: ENQUEUE(Q, "A"), ENQUEUE(Q, "B"), ENQUEUE(Q, "C"), DEQUEUE(Q). State which value DEQUEUE removed and the final queue contents.
A singly linked list is built from nodes. Each node has two fields. (a) Name the two fields and explain what each stores. (b) Explain what it means for the pointer field of the LAST node to be NULL. (c) State the name of the special pointer that identifies the start of the list.
An empty stack S supports PUSH, POP and PEEK (PEEK returns the top value WITHOUT removing it). Trace the following sequence of operations and list the value returned by each POP and PEEK, and the final stack contents: PUSH(S, 5); PUSH(S, 8); POP(S); PUSH(S, 3); PEEK(S); POP(S); POP(S).
An empty queue Q supports ENQUEUE and DEQUEUE. Trace the following operations and list the value returned by each DEQUEUE, and the final queue contents: ENQUEUE(Q, "A"); ENQUEUE(Q, "B"); DEQUEUE(Q); ENQUEUE(Q, "C"); ENQUEUE(Q, "D"); DEQUEUE(Q); DEQUEUE(Q). (Front of queue is shown on the left.)
A singly linked list has HEAD pointing to the first node. The list contains three nodes: Node1 (Data=10, Next=Node2), Node2 (Data=20, Next=Node3), Node3 (Data=30, Next=NULL). Write pseudocode (using a pointer variable Current) to traverse the list from HEAD and OUTPUT every Data value. Then state what value Current holds when the traversal ends.
A stack is implemented using a fixed-size array of capacity 5. (a) Explain what is meant by "stack overflow" and give the condition that triggers it. (b) Explain what is meant by "stack underflow" and give the condition that triggers it. (c) State the value of the Top pointer in each case.
A stack is implemented using a 1D array Stack[1:5] of INTEGER. Write pseudocode for a PUSH procedure that takes a value and adds it to the top of the stack. Provide TWO valid approaches — Approach 1 uses a Top pointer that starts at 0 (increment FIRST, then store); Approach 2 uses a Top pointer that starts at 1 (store FIRST, then increment). Both must reject overflow correctly.
A queue is implemented using a 1D array Queue[1:5] of INTEGER. Write pseudocode for a DEQUEUE procedure that removes and outputs the front item. Provide TWO valid approaches — Approach 1 uses a LINEAR queue: shift every remaining item one slot to the left after removing the front; Approach 2 uses a CIRCULAR queue with Front and Rear pointers that wrap around using MOD.
Module 6
Exam Technique
The skills examiners actually test: tracing, designing from briefs, choosing test data, judging efficiency and commenting code.
The following pseudocode computes the area of a rectangle. Add a comment on EACH line using the Cambridge // single-line comment symbol to explain what that line does.
DECLARE Length, Width, Area : REAL
INPUT Length
INPUT Width
Area <- Length * Width
OUTPUT AreaComplete the trace table for the following pseudocode. Show the values of I and Sum after each iteration of the FOR loop and the final OUTPUT.
DECLARE I, Sum : INTEGER
Sum <- 0
FOR I <- 1 TO 5
Sum <- Sum + I
NEXT I
OUTPUT SumA program inputs a student's exam mark (INTEGER) and awards a grade. The valid range is 0 to 100 inclusive (marks below 0 or above 100 are invalid). Give ONE example of each of the following types of test data, with a brief reason: (a) normal data, (b) boundary data (give TWO boundary values), (c) abnormal data.
A program is described as follows: "Input a number N. Then input N more numbers and output their total." Convert this design into Cambridge pseudocode. Use a FOR loop and an INTEGER variable Total to accumulate the sum.
The user enters these values in order: 10, 20, 30, -1. Complete the trace table showing Count and Total after each pass of the WHILE loop, and the final OUTPUT values.
DECLARE Value, Count, Total : INTEGER
Count <- 0
Total <- 0
OUTPUT "Enter a value (-1 to stop): "
INPUT Value
WHILE Value <> -1 DO
Count <- Count + 1
Total <- Total + Value
OUTPUT "Enter a value (-1 to stop): "
INPUT Value
ENDWHILE
OUTPUT "Count: ", Count
OUTPUT "Total: ", TotalA program inputs three REAL values representing the lengths of the sides of a triangle, then computes and outputs its area. Valid triangles have: all three sides positive (> 0), and the sum of any two sides greater than the third. Give ONE example of each type of test data and explain what each tests: (a) normal, (b) boundary (give TWO values), (c) abnormal (give TWO values).
A student has written two algorithms for an array of n items: a LINEAR SEARCH (looks for a target by comparing each element one-by-one) and a BUBBLE SORT (repeatedly compares adjacent pairs and swaps them until no swaps are needed). (a) State the worst-case time complexity of each in big-O notation. (b) For an array of 1000 items, roughly how many comparisons does each make in the worst case? (c) State ONE situation in which each algorithm is preferred.
A program is described by the following steps: (1) Input the scores of 30 students into an array Scores. (2) Compute the class average. (3) Count how many students scored above the average. (4) Output the average and the count. Convert this design into Cambridge pseudocode. Use INTEGER arrays and a REAL average.
The following pseudocode uses NESTED FOR loops to print every ordered pair (R, C) for R = 1 to 2 and C = 1 to 3. Rewrite it using a SINGLE loop. Provide TWO valid approaches — Approach 1 keeps the nested structure but uses nested WHILE loops; Approach 2 uses a SINGLE WHILE loop with a counter K from 1 to 6 and computes R and C from K using DIV and MOD.
DECLARE R, C : INTEGER
FOR R <- 1 TO 2
FOR C <- 1 TO 3
OUTPUT R, ", ", C
NEXT C
NEXT RThe factorial of a non-negative integer n is n! = n * (n-1) * ... * 2 * 1, with 0! = 1. Write pseudocode to compute n! iteratively (no recursion). Provide TWO valid approaches — Approach 1 uses a FORWARD loop from 1 to n accumulating a product; Approach 2 uses a BACKWARD loop from n down to 1. For each, trace the values of the loop counter and the running product when n = 5.