Paper 2: Pseudocode step by step

Paper 2: Pseudocode step by step

Paper 2 pseudocode: the complete guide

Pseudocode O Level 60 min read

On this page
  1. Paper 2 at a glance
  2. The rules of writing pseudocode
  3. Input, output and operators
  4. Selection: IF and CASE
  5. Iteration: FOR, WHILE and REPEAT
  6. Totalling, counting, maximum, minimum, average
  7. String handling
  8. Validation, verification and test data
  9. Procedures, functions and parameters
  10. Arrays, linear search and bubble sort
  11. File handling
  12. Trace tables and finding errors
  13. The 15-mark scenario question
  14. One-page reference card

Every pseudocode topic on Cambridge O Level Computer Science (2210) Paper 2, in the exact style the exam prints. Each topic has a worked example and questions like the real paper. Try each one in the space, then press Check my answer and tick it off.

14 short topics39 questions to try52 answers tested by running them
0 of 39 done
01

Paper 2 at a glance

0478 / 2210 syllabus for 2026–2028 · Topics 7 to 10

Big ideaPaper 2 rewards clear, exact steps. You already think in steps; this paper teaches you to write them down.

Paper 2 Algorithms, Programming and Logic is 1 hour 45 minutes, 75 marks, every question compulsory, no calculator. Topics 7 (algorithm design) and 8 (programming) are where pseudocode lives; topics 9 (databases and SQL) and 10 (Boolean logic) are the rest of the paper and are not covered here.

Part of the paperWhat students doTypical marks
Short questionsdata types, validation checks, test data, loop types, library routines1 to 4 each
Complete / correct an algorithmfill in gaps, find and fix errors by line number4 to 6
Trace tablesdry-run an algorithm or flowchart with given data4 to 6
Write an algorithmshort pseudocode for a stated task4 to 8
Scenario question (always last)a full program for an unseen context, about 30 minutes15 (AO2 9 + AO3 6)
02

The rules of writing pseudocode

Syllabus 8.1.1 · 8.1.2 · pseudocode guide in section 4

Big ideaPseudocode is just English with a few fixed words. Learn the ten rules once and every question reads easier.

Cambridge prints every algorithm in one fixed style. Students who write in the same style read questions faster and lose fewer marks to ambiguity.

RuleExample
Keywords in CAPITALSIF FOR REPEAT OUTPUT
Identifiers in PascalCase: start with a capital letter, only letters and digits, no spaces or _NumberOfPlayers TotalToPay
Assignment uses the arrow ← (never =)Counter ← Counter + 1
Declare a variable with its data typeDECLARE Counter : INTEGER
A constant holds a literal value onlyCONSTANT HourlyRate ← 6.50
Comments start with //// works out the total
Indent the inside of a structure by 4 spaces; THEN, ELSE and CASE lines by 2see every example below

The five data types

TypeHoldsLiteral looks likeUse it for
INTEGERwhole numbers5 -3counts, ages, number of items
REALnumbers with a fractional part4.7 0.0 -4.0prices, heights, averages
CHARexactly one character'x' '@'a grade letter, a menu choice
STRINGzero or more characters"Hello" ""names, codes, phone numbers
BOOLEANTRUE or FALSETRUE FALSEflags: Found, Swap, Valid
A complete short program ✓ tested
// Works out the cost of a cinema trip
CONSTANT TicketPrice ← 8.50
DECLARE Tickets : INTEGER
DECLARE Cost : REAL
OUTPUT "How many tickets?"
INPUT Tickets
Cost ← Tickets * TicketPrice
OUTPUT "Total cost: $", Cost
Screen
How many tickets?
3
Total cost: $25.5

Your turn

Q2.15 marks

Give the most suitable data type for each item.

ItemData type
(a) the number of passengers on a bus
(b) a person's height in metres
(c) whether a door is open
(d) the first letter of a surname
(e) a telephone number such as 03001234567
Check my answermodel answer and marking points
ItemAnswerWhy
(a)INTEGERwhole number
(b)REALhas a decimal part, e.g. 1.62
(c)BOOLEANonly two states
(d)CHARone character
(e)STRINGleading 0 must be kept; no arithmetic is done with it

1 mark each. Common wrong answer: INTEGER for (e).

Q2.24 marks

This pseudocode contains four errors. Identify each error and write the corrected statement.

01DECLARE 1stScore : INTEGER02DECLARE Average Mark : REAL03CONSTANT PassMark ← Score + 1004Total = Total + 1
Check my answermodel answer and marking points
LineErrorCorrection
01identifier starts with a digitDECLARE FirstScore : INTEGER
02identifier contains a spaceDECLARE AverageMark : REAL
03a constant must be a literal valueCONSTANT PassMark ← 50
04assignment uses ← not =Total ← Total + 1
Q2.33 marks

A shop adds a sales tax of 20% to every price. Explain two reasons for storing the tax rate as a constant, and write the statement that declares it.

Check my answermodel answer and marking points
  • Readable: Price * TaxRate explains itself, 0.2 does not.
  • If the rate changes, it is changed in one place only.
  • The value cannot be changed by mistake while the program runs.
CONSTANT TaxRate ← 0.2

Any two reasons + the declaration.

03

Input, output and operators

Syllabus 8.1.3 · 8.1.4(f) · 8.1.7

Big ideaComputers only do maths and comparisons. DIV and MOD are the two that surprise people, and they are easy.

Every INPUT in an exam answer should come after an OUTPUT that tells the user what to type. OUTPUT can show several values separated by commas.

OperatorMeaningExampleResult
+ – * /add, subtract, multiply, divide17 / 44.25
^raised to the power of2 ^ 38
DIV(a, b)whole-number division (remainder thrown away)DIV(17, 4)4
MOD(a, b)the remainderMOD(17, 4)1
= < <= > >= <>compare; the result is BOOLEAN5 <> 4TRUE
AND OR NOTcombine conditions(7 > 3) AND (2 > 5)FALSE
ROUND(x, places)round to a number of decimal placesROUND(3.14159, 2)3.14
RANDOM()a random number from 0 to 1ROUND(RANDOM() * 5, 0) + 1a whole number 1 to 6
DIV and MOD together split a quantity ✓ tested
OUTPUT "Enter the number of minutes"
INPUT TotalMinutes
Hours ← DIV(TotalMinutes, 60)
Minutes ← MOD(TotalMinutes, 60)
OUTPUT TotalMinutes, " minutes is ", Hours, " hours and ", Minutes, " minutes"

Your turn

Q3.16 marks

State the value of each expression.

ExpressionValue
DIV(23, 4)
MOD(23, 4)
2 ^ 3 + 1
17 / 4
(7 > 3) AND (2 > 5)
NOT (4 <> 4)
Check my answermodel answer and marking points
ExpressionValue
DIV(23, 4)5
MOD(23, 4)3
2 ^ 3 + 19
17 / 44.25
(7 > 3) AND (2 > 5)FALSE
NOT (4 <> 4)TRUE
Checked by running it ✓ tested
OUTPUT DIV(23, 4), " ", MOD(23, 4), " ", 2 ^ 3 + 1, " ", 17 / 4, " ", (7 > 3) AND (2 > 5), " ", NOT (4 <> 4)
Q3.24 marks

Write pseudocode to input a number of seconds and output it as minutes and seconds. For example, 200 is output as 3 minutes 20 seconds.

Check my answermodel answer and marking points
✓ tested
OUTPUT "Enter a number of seconds"
INPUT Seconds
Minutes ← DIV(Seconds, 60)
Remainder ← MOD(Seconds, 60)
OUTPUT Minutes, " minutes ", Remainder, " seconds"
  • 1 prompt + INPUT
  • 1 DIV by 60
  • 1 MOD by 60
  • 1 OUTPUT with both values and labels
Q3.33 marks

Write a condition for each of these. (a) Age is from 13 to 19 inclusive. (b) Letter is a vowel (lower case only). (c) Score is not zero.

Check my answermodel answer and marking points
// (a)
Age >= 13 AND Age <= 19
// (b)
Letter = 'a' OR Letter = 'e' OR Letter = 'i' OR Letter = 'o' OR Letter = 'u'
// (c)
Score <> 0

(b) Each comparison must name the variable again: Letter = 'a' OR 'e' is wrong.

04

Selection: IF and CASE

Syllabus 8.1.4(b) · 8.1.5

Big ideaIF is how a program makes a choice. Ask the biggest question first and work down.

IF tests any condition. CASE picks one branch from a list of single values. Use IF for ranges (marks, prices, ages) and CASE for menus and codes.

Nested IF: test the highest band first ✓ tested
OUTPUT "Enter the mark (0 to 100)"
INPUT Mark
IF Mark >= 80
  THEN
    Grade ← 'A'
  ELSE
    IF Mark >= 60
      THEN
        Grade ← 'B'
      ELSE
        IF Mark >= 40
          THEN
            Grade ← 'C'
          ELSE
            Grade ← 'U'
        ENDIF
    ENDIF
ENDIF
OUTPUT "Grade: ", Grade
CASE for a menu, with OTHERWISE catching anything else ✓ tested
OUTPUT "Enter two numbers"
INPUT A
INPUT B
OUTPUT "Choose 1 Add, 2 Subtract, 3 Multiply"
INPUT Choice
CASE OF Choice
  1 : OUTPUT A + B
  2 : OUTPUT A - B
  3 : OUTPUT A * B
  OTHERWISE OUTPUT "Invalid choice"
ENDCASE

Your turn

Q4.15 marks

A car park charges nothing for up to 2 hours, $3 for more than 2 hours up to 5 hours, and $8 for more than 5 hours. Write pseudocode to input the hours parked and output the charge.

Check my answermodel answer and marking points
✓ tested
OUTPUT "How many hours were you parked?"
INPUT Hours
IF Hours <= 2
  THEN
    Charge ← 0
  ELSE
    IF Hours <= 5
      THEN
        Charge ← 3
      ELSE
        Charge ← 8
    ENDIF
ENDIF
OUTPUT "Charge: $", Charge
  • prompt and INPUT
  • first test (≤ 2) → 0
  • second test (≤ 5) → 3
  • otherwise → 8
  • OUTPUT with label
Q4.24 marks

Write a CASE statement that inputs a day number 1 to 7 and outputs the day's name (1 = Monday). Any other number outputs Invalid day number.

Check my answermodel answer and marking points
✓ tested
INPUT DayNumber
CASE OF DayNumber
  1 : OUTPUT "Monday"
  2 : OUTPUT "Tuesday"
  3 : OUTPUT "Wednesday"
  4 : OUTPUT "Thursday"
  5 : OUTPUT "Friday"
  6 : OUTPUT "Saturday"
  7 : OUTPUT "Sunday"
  OTHERWISE OUTPUT "Invalid day number"
ENDCASE
  • CASE OF DayNumber … ENDCASE
  • seven correct branches
  • OTHERWISE with the message
  • INPUT before CASE
Q4.3Find the error3 marks

This algorithm should output Distinction for 75 or more, Pass for 40 to 74 and Fail below 40. Explain why it does not work, and correct it.

01IF Mark >= 4002  THEN03    Result ← "Pass"04  ELSE05    IF Mark >= 7506      THEN07        Result ← "Distinction"08      ELSE09        Result ← "Fail"10    ENDIF11ENDIF
Check my answermodel answer and marking points

A mark of 80 passes the first test (80 ≥ 40), so it gets Pass; the Distinction branch can never be reached, because it only runs when Mark is below 40. Test 75 first:

✓ tested
IF Mark >= 75
  THEN
    Result ← "Distinction"
  ELSE
    IF Mark >= 40
      THEN
        Result ← "Pass"
      ELSE
        Result ← "Fail"
    ENDIF
ENDIF
OUTPUT Result
05

Iteration: FOR, WHILE and REPEAT

Syllabus 8.1.4(c)

Big ideaA loop saves you writing the same line 30 times. The only question is: how does it know when to stop?

LoopTypeCondition testedRunsChoose it when
FOR … NEXTcount-controlled—a fixed number of timesyou know how many times (30 students)
WHILE … DO … ENDWHILEpre-conditionbefore the body0 or more timesit may not need to run at all (a rogue value could come first)
REPEAT … UNTILpost-conditionafter the bodyat least oncethe body must happen once (ask for input, then check it)
FOR with a STEP: the step can be negative ✓ tested
FOR Count ← 10 TO 0 STEP -2
    OUTPUT Count
NEXT Count
WHILE with a rogue value: input once before the loop and again at the end of the body ✓ tested
Total ← 0
OUTPUT "Enter a number (-1 to stop)"
INPUT Number
WHILE Number <> -1 DO
    Total ← Total + Number
    OUTPUT "Enter a number (-1 to stop)"
    INPUT Number
ENDWHILE
OUTPUT "Total is ", Total
REPEAT: the body always runs once ✓ tested
REPEAT
    OUTPUT "Enter your age (11 to 18)"
    INPUT Age
UNTIL Age >= 11 AND Age <= 18

Your turn

Q5.13 marks

Write a FOR loop that outputs the 5 times table from 5 x 1 = 5 to 5 x 12 = 60.

Check my answermodel answer and marking points
✓ tested
FOR Count ← 1 TO 12
    OUTPUT "5 x ", Count, " = ", 5 * Count
NEXT Count
  • FOR 1 TO 12 … NEXT
  • 5 * Count
  • OUTPUT with the text in the right order
Q5.24 marks

Rewrite this algorithm using (a) a REPEAT … UNTIL loop and (b) a WHILE loop.

FOR Count ← 1 TO 5
    OUTPUT Count * Count
NEXT Count
Check my answermodel answer and marking points

(a)

✓ tested
Count ← 1
REPEAT
    OUTPUT Count * Count
    Count ← Count + 1
UNTIL Count > 5

(b)

✓ tested
Count ← 1
WHILE Count <= 5 DO
    OUTPUT Count * Count
    Count ← Count + 1
ENDWHILE

Marks: start value set before the loop, Count increased inside the loop, correct stop condition for each.

Q5.33 marks

Name the most suitable loop for each task and give a reason. (a) Input the marks of 30 students. (b) Keep asking for a password until it is correct. (c) Add up prices until the user enters 0 (the first value could be 0).

Check my answermodel answer and marking points
  • (a) FOR: the number of repetitions (30) is known.
  • (b) REPEAT … UNTIL: the password must be asked for at least once.
  • (c) WHILE: the condition is checked first, so the loop may run zero times.
Q5.46 marks

Write a number-guessing game. The program picks a random whole number from 1 to 100. The user keeps guessing; after each wrong guess output Too high or Too low. When the guess is correct output how many guesses were taken.

Check my answermodel answer and marking points
Secret ← ROUND(RANDOM() * 99, 0) + 1
Attempts ← 0
REPEAT
    OUTPUT "Guess the number (1 to 100)"
    INPUT Guess
    Attempts ← Attempts + 1
    IF Guess > Secret
      THEN
        OUTPUT "Too high"
    ENDIF
    IF Guess < Secret
      THEN
        OUTPUT "Too low"
    ENDIF
UNTIL Guess = Secret
OUTPUT "Correct! You took ", Attempts, " guesses"
  • random number 1 to 100
  • count set to 0, increased each guess
  • loop until correct
  • Too high / Too low with selection
  • final OUTPUT with the count
  • prompt before each INPUT
06

Totalling, counting, maximum, minimum, average

Syllabus 7.4 · 8.1.4(d)

Big ideaFour tiny patterns (total, count, highest, lowest) are in almost every paper. Learn their shape and they are free marks.

Four patterns appear in almost every Paper 2. Teach them as fixed shapes students can write without thinking.

MethodBefore the loopInside the loop
TotallingTotal ← 0Total ← Total + Value
CountingCount ← 0IF condition THEN Count ← Count + 1
MaximumHighest ← a very low value (or the first value)IF Value > Highest THEN Highest ← Value
MinimumLowest ← a very high value (or the first value)IF Value < Lowest THEN Lowest ← Value
Average—after the loop: Average ← Total / NumberOfValues
All four methods in one loop ✓ tested
// one week of temperatures: total, hot days, highest, lowest, average
Total ← 0
HotDays ← 0
Highest ← -100
Lowest ← 100
FOR Day ← 1 TO 7
    OUTPUT "Enter the temperature for day ", Day
    INPUT Temperature
    Total ← Total + Temperature
    IF Temperature > 25
      THEN
        HotDays ← HotDays + 1
    ENDIF
    IF Temperature > Highest
      THEN
        Highest ← Temperature
    ENDIF
    IF Temperature < Lowest
      THEN
        Lowest ← Temperature
    ENDIF
NEXT Day
Average ← ROUND(Total / 7, 1)
OUTPUT "Average: ", Average, " Highest: ", Highest, " Lowest: ", Lowest
OUTPUT "Days above 25: ", HotDays
Screen
… (7 prompts) …
Average: 24.1 Highest: 31 Lowest: 18
Days above 25: 3

Your turn

Q6.16 marks

Write pseudocode to input the prices of 10 items. Output the total cost, the average price rounded to 2 decimal places, and how many items cost more than $50.

Check my answermodel answer and marking points
✓ tested
Total ← 0
Expensive ← 0
FOR Item ← 1 TO 10
    OUTPUT "Enter the price of item ", Item
    INPUT Price
    Total ← Total + Price
    IF Price > 50
      THEN
        Expensive ← Expensive + 1
    ENDIF
NEXT Item
OUTPUT "Total: $", Total
OUTPUT "Average price: $", ROUND(Total / 10, 2)
OUTPUT "Items over $50: ", Expensive
  • Total and count set to 0 before the loop
  • loop 10 times with prompt and INPUT
  • Total ← Total + Price
  • IF Price > 50 then count + 1
  • average with ROUND(…, 2) after the loop
  • three outputs with labels
Q6.2Complete the algorithm5 marks

The numbers input are all between 1 and 999. Complete the algorithm so that it outputs the largest and smallest of 50 numbers.

Largest ←  
Smallest ← 1000
FOR Count ← 1 TO  
    INPUT Number
    IF Number > Largest
      THEN
          ← Number
    ENDIF
    IF  
      THEN
        Smallest ← Number
    ENDIF
NEXT  
OUTPUT "Largest: ", Largest, " Smallest: ", Smallest
Check my answermodel answer and marking points
  1. 0 (any value below 1)
  2. 50
  3. Largest
  4. Number < Smallest
  5. Count
Completed ✓ tested
Largest ← 0
Smallest ← 1000
FOR Count ← 1 TO 50
    INPUT Number
    IF Number > Largest
      THEN
        Largest ← Number
    ENDIF
    IF Number < Smallest
      THEN
        Smallest ← Number
    ENDIF
NEXT Count
OUTPUT "Largest: ", Largest, " Smallest: ", Smallest
Q6.36 marks

A rain gauge records rainfall in millimetres for 30 days. Write pseudocode to input the 30 readings and output the total rainfall, the number of dry days (0 mm) and the day number with the most rain.

Check my answermodel answer and marking points
✓ tested
Total ← 0
DryDays ← 0
Wettest ← -1
WettestDay ← 0
FOR Day ← 1 TO 30
    OUTPUT "Enter the rainfall in mm for day ", Day
    INPUT Rain
    Total ← Total + Rain
    IF Rain = 0
      THEN
        DryDays ← DryDays + 1
    ENDIF
    IF Rain > Wettest
      THEN
        Wettest ← Rain
        WettestDay ← Day
    ENDIF
NEXT Day
OUTPUT "Total rainfall: ", Total, " mm"
OUTPUT "Dry days: ", DryDays
OUTPUT "Wettest day: day ", WettestDay, " with ", Wettest, " mm"

Key idea: store the day number at the same moment as the new maximum (WettestDay ← Day).

07

String handling

Syllabus 8.1.4(e)

Big ideaA string is a row of boxes, one letter in each. SUBSTRING just picks some boxes out.

FunctionReturnsExampleResult
LENGTH(s)number of charactersLENGTH("Happy Days")10
SUBSTRING(s, start, length)part of the string; position 1 is the first characterSUBSTRING("Happy Days", 1, 5)"Happy"
UCASE(s)upper case copyUCASE("Happy")"HAPPY"
LCASE(s)lower case copyLCASE('W')'w'
The standard shape: loop from 1 to LENGTH, take one character at a time ✓ tested
OUTPUT "Enter a sentence"
INPUT Sentence
Vowels ← 0
FOR Position ← 1 TO LENGTH(Sentence)
    Letter ← LCASE(SUBSTRING(Sentence, Position, 1))
    IF Letter = "a" OR Letter = "e" OR Letter = "i" OR Letter = "o" OR Letter = "u"
      THEN
        Vowels ← Vowels + 1
    ENDIF
NEXT Position
OUTPUT "Number of vowels: ", Vowels

Your turn

Q7.14 marks

State what each function call returns.

CallReturns
LENGTH("Computer Science")
SUBSTRING("Computer Science", 10, 3)
UCASE("igcse")
LCASE(SUBSTRING("PAKISTAN", 1, 3))
Check my answermodel answer and marking points
CallReturns
LENGTH("Computer Science")16 (the space counts)
SUBSTRING("Computer Science", 10, 3)"Sci"
UCASE("igcse")"IGCSE"
LCASE(SUBSTRING("PAKISTAN", 1, 3))"pak"
Checked by running it ✓ tested
OUTPUT LENGTH("Computer Science"), SUBSTRING("Computer Science", 10, 3), UCASE("igcse"), LCASE(SUBSTRING("PAKISTAN", 1, 3))
Q7.26 marks

A password is strong if it has at least 8 characters and contains at least one digit. Write pseudocode to input a password and output Strong password or Weak password.

Check my answermodel answer and marking points
✓ tested
OUTPUT "Enter a password"
INPUT Password
HasDigit ← FALSE
FOR Position ← 1 TO LENGTH(Password)
    Character ← SUBSTRING(Password, Position, 1)
    IF Character >= "0" AND Character <= "9"
      THEN
        HasDigit ← TRUE
    ENDIF
NEXT Position
IF LENGTH(Password) >= 8 AND HasDigit = TRUE
  THEN
    OUTPUT "Strong password"
  ELSE
    OUTPUT "Weak password"
ENDIF

Also tested: abc123 gives Weak password (too short).

  • prompt + INPUT
  • Boolean flag set to FALSE before the loop
  • loop through every character with SUBSTRING
  • digit test
  • length test with LENGTH
  • both conditions joined with AND, two outputs
Q7.33 marks

Write pseudocode to input a word and output its letters in reverse order, one letter per line.

Check my answermodel answer and marking points
✓ tested
OUTPUT "Enter a word"
INPUT Word
FOR Position ← LENGTH(Word) TO 1 STEP -1
    OUTPUT SUBSTRING(Word, Position, 1)
NEXT Position
  • loop starts at LENGTH(Word)
  • STEP -1 down to 1
  • SUBSTRING(Word, Position, 1)
08

Validation, verification and test data

Syllabus 7.5 · 7.6

Big ideaNever trust what a user types. A validation loop keeps asking until the answer makes sense.

Validation is the computer checking that data is reasonable and follows the rules. Verification checks that data was copied or typed correctly. Valid data can still be wrong: 17 is a valid age, even if the student is 15.

CheckWhat it testsPseudocode idea
Rangebetween a lower and an upper limitMark < 0 OR Mark > 100
Lengthnumber of charactersLENGTH(Password) < 8
Typethe right kind of data, e.g. a whole numberNumber <> ROUND(Number, 0)
Presencesomething has been enteredName = ""
Formata set pattern, e.g. two letters then four digitsSUBSTRING each position and test it
Check digitan extra digit calculated from the others (ISBN, barcodes) catches typing errorsexplained, not usually coded
The validation loop to learn by heart: input, then repeat while the data is invalid ✓ tested
OUTPUT "Enter a mark between 0 and 100"
INPUT Mark
WHILE Mark < 0 OR Mark > 100 DO
    OUTPUT "Invalid. The mark must be between 0 and 100. Try again"
    INPUT Mark
ENDWHILE
VerificationHow
Double entrythe data is typed twice and the two copies are compared; a mismatch means re-enter
Visual checkthe user reads the data on screen and confirms it matches the original

Test data

For an input that must be a whole number from 1 to 50:

TypeMeaningExample values
Normalordinary data that should be accepted25, 7
Abnormaldata that should be rejected-5, 75, "ten"
Extremethe largest and smallest accepted values1 and 50
Boundaryeach limit and the value just outside it0 and 1, 50 and 51

Your turn

Q8.14 marks

Name the validation check that would be used for each of these.

RuleCheck
(a) a surname must be entered
(b) a month number must be 1 to 12
(c) a username must be 6 to 12 characters
(d) a product code must be like AB1234
Check my answermodel answer and marking points
RuleCheck
(a)presence check
(b)range check
(c)length check
(d)format check
Q8.24 marks

An age must be a whole number from 11 to 18. Give one example of each type of test data and the reason for using it: normal, abnormal, extreme, boundary.

Check my answermodel answer and marking points
TypeExampleReason
Normal14should be accepted
Abnormal25 (or -3, or "twelve")should be rejected
Extreme18 (or 11)largest / smallest value that is accepted
Boundary18 and 19 (or 10 and 11)accepted limit and the rejected value next to it
Q8.36 marks

Write pseudocode to set a new password. It must be at least 8 characters long (length check), then be verified by double entry. Keep asking until the two entries match, then output Password saved.

Check my answermodel answer and marking points
✓ tested
REPEAT
    OUTPUT "Enter a new password (at least 8 characters)"
    INPUT Password
    WHILE LENGTH(Password) < 8 DO
        OUTPUT "Too short. Enter at least 8 characters"
        INPUT Password
    ENDWHILE
    OUTPUT "Enter the password again"
    INPUT Check
    IF Check <> Password
      THEN
        OUTPUT "The passwords do not match. Start again"
    ENDIF
UNTIL Check = Password
OUTPUT "Password saved"
  • prompts + inputs
  • length check with LENGTH and a loop
  • second entry input
  • comparison of the two entries
  • outer loop repeats until they match
  • final message
Q8.4Format check5 marks

A product code must be 6 characters: two upper case letters followed by four digits (e.g. AB1234). Write pseudocode to input a code and output Valid or Invalid.

Check my answermodel answer and marking points
✓ tested
OUTPUT "Enter the product code"
INPUT ProductCode
Valid ← TRUE
IF LENGTH(ProductCode) <> 6
  THEN
    Valid ← FALSE
  ELSE
    FOR Position ← 1 TO 6
        Character ← SUBSTRING(ProductCode, Position, 1)
        IF Position <= 2
          THEN
            IF Character < "A" OR Character > "Z"
              THEN
                Valid ← FALSE
            ENDIF
          ELSE
            IF Character < "0" OR Character > "9"
              THEN
                Valid ← FALSE
            ENDIF
        ENDIF
    NEXT Position
ENDIF
IF Valid = TRUE
  THEN
    OUTPUT "Valid"
  ELSE
    OUTPUT "Invalid"
ENDIF

Also tested: A12345 and AB123 give Invalid.

  • length check first
  • loop through the characters with SUBSTRING
  • letters test for positions 1–2
  • digits test for positions 3–6
  • flag + correct output
09

Procedures, functions and parameters

Syllabus 8.1.6 · 8.1.7 · 8.1.8

Big ideaGive a job a name, write it once, use it anywhere. That is all a procedure or function is.

ProcedureFunction
Returns a value?noyes, exactly one, with RETURN
HeaderPROCEDURE Name(P : TYPE)FUNCTION Name(P : TYPE) RETURNS TYPE
Called withCALL Name(…) as a statement on its owninside an expression: X ← Name(…) or OUTPUT Name(…)
Ends withENDPROCEDUREENDFUNCTION

A parameter is the variable in the header that receives a value when the subroutine is called (up to three in this syllabus). A local variable is declared inside a subroutine and only exists there; a global variable is declared in the main program and can be used anywhere. Library routines are ready-made: MOD, DIV, ROUND, RANDOM, LENGTH, SUBSTRING, UCASE, LCASE.

A procedure and a function, defined first, then used ✓ tested
PROCEDURE ShowResult(StudentName : STRING, Mark : INTEGER)
    OUTPUT StudentName, " scored ", Mark
    IF Mark >= 50
      THEN
        OUTPUT "Well done"
    ENDIF
ENDPROCEDURE

FUNCTION Percentage(Mark : INTEGER, OutOf : INTEGER) RETURNS REAL
    RETURN ROUND(Mark / OutOf * 100, 1)
ENDFUNCTION

CALL ShowResult("Sara", 62)
OUTPUT "Percentage: ", Percentage(62, 75)
Local and global variables ✓ tested
DECLARE Total : INTEGER          // global: usable anywhere

PROCEDURE AddBonus(Points : INTEGER)
    DECLARE Bonus : INTEGER      // local: exists only inside AddBonus
    Bonus ← Points * 2
    Total ← Total + Bonus
ENDPROCEDURE

Total ← 10
CALL AddBonus(5)
OUTPUT Total

Your turn

Q9.14 marks

Explain two differences between a procedure and a function, and state what is meant by a parameter.

Check my answermodel answer and marking points
  • A function returns a value; a procedure does not.
  • A function is called as part of an expression (e.g. on the right of ←); a procedure is called with CALL as its own statement.
  • A function header states the data type it RETURNS.
  • Parameter: a variable in the subroutine header that receives a value passed in when it is called.
Q9.25 marks

Write a function Largest that takes three integers and returns the largest. Then write a statement that outputs the largest of 4, 11 and 7.

Check my answermodel answer and marking points
✓ tested
FUNCTION Largest(A : INTEGER, B : INTEGER, C : INTEGER) RETURNS INTEGER
    DECLARE Biggest : INTEGER
    Biggest ← A
    IF B > Biggest
      THEN
        Biggest ← B
    ENDIF
    IF C > Biggest
      THEN
        Biggest ← C
    ENDIF
    RETURN Biggest
ENDFUNCTION

OUTPUT Largest(4, 11, 7)
  • header with three parameters and RETURNS INTEGER
  • comparisons to find the largest
  • RETURN the value
  • ENDFUNCTION
  • call inside OUTPUT (no CALL keyword)
Q9.34 marks

Write a function ToFahrenheit that converts a Celsius temperature using F = C × 9 / 5 + 32. Use it in a loop that outputs the conversions for 0, 20, 40, 60, 80 and 100 °C.

Check my answermodel answer and marking points
✓ tested
FUNCTION ToFahrenheit(Celsius : REAL) RETURNS REAL
    RETURN Celsius * 9 / 5 + 32
ENDFUNCTION

FOR Temperature ← 0 TO 100 STEP 20
    OUTPUT Temperature, "C = ", ToFahrenheit(Temperature), "F"
NEXT Temperature
  • function header with parameter and RETURNS REAL
  • correct formula returned
  • FOR with STEP 20
  • function called inside the loop with the loop variable
Q9.43 marks

In the AddBonus example above, identify one local and one global variable, and give one reason why local variables are good practice.

Check my answermodel answer and marking points
  • Local: Bonus (or the parameter Points). Global: Total.
  • Reason: a local variable cannot be changed by mistake elsewhere in the program; the same name can be reused in other subroutines; memory is freed when the subroutine ends.
10

Arrays, linear search and bubble sort

Syllabus 8.2 · 7.4

Big ideaAn array is a numbered list in one variable. A loop plus an array can handle 1000 students as easily as 3.

An array is a fixed number of values of the same type under one name, reached by an index. The first index is usually 1. A 2D array has a row index and a column index.

Declaring and using 1D and 2D arrays
DECLARE StudentNames : ARRAY[1:30] OF STRING
DECLARE Marks : ARRAY[1:30, 1:3] OF INTEGER    // 30 students x 3 tests

StudentNames[1] ← "Ali"
Marks[1, 2] ← 74                              // student 1, test 2
2D array: nested loops, outer = rows, inner = columns ✓ tested
// Readings[1:7, 1:3] holds 3 temperature readings for each of 7 days
FOR Day ← 1 TO 7
    DayTotal ← 0
    FOR Reading ← 1 TO 3
        DayTotal ← DayTotal + Readings[Day, Reading]
    NEXT Reading
    OUTPUT "Day ", Day, " average: ", ROUND(DayTotal / 3, 1)
NEXT Day

Linear search

Check each element in turn until the item is found or the end is reached. Using WHILE with a Found flag stops as soon as the item is found.

Linear search ✓ tested
// Names[1:30] already holds 30 names
OUTPUT "Enter the name to find"
INPUT SearchName
Found ← FALSE
Index ← 1
WHILE Found = FALSE AND Index <= 30 DO
    IF Names[Index] = SearchName
      THEN
        Found ← TRUE
      ELSE
        Index ← Index + 1
    ENDIF
ENDWHILE
IF Found = TRUE
  THEN
    OUTPUT SearchName, " found at position ", Index
  ELSE
    OUTPUT SearchName, " not found"
ENDIF

Bubble sort

Compare each pair of neighbours and swap them if they are in the wrong order. After each pass the largest value has “bubbled” to the end, so the next pass can stop one place earlier. Stop when a whole pass makes no swaps.

Bubble sort in the Cambridge style (same shape as 0478/21/M/J/26 Q4) ✓ tested
// Scores[1:10] already holds 10 scores: sort into ascending order
Last ← 10
REPEAT
    Swap ← FALSE
    FOR Index ← 1 TO Last - 1
        IF Scores[Index] > Scores[Index + 1]
          THEN
            Temp ← Scores[Index]
            Scores[Index] ← Scores[Index + 1]
            Scores[Index + 1] ← Temp
            Swap ← TRUE
        ENDIF
    NEXT Index
    Last ← Last - 1
UNTIL NOT Swap OR Last = 1

Your turn

Q10.13 marks

(a) Declare an array to hold 25 names. (b) Declare a 2D array of integers with 6 rows and 4 columns called Points. (c) Write a statement that stores 75 in row 3, column 2 of Points.

Check my answermodel answer and marking points
✓ tested
DECLARE Names : ARRAY[1:25] OF STRING
DECLARE Points : ARRAY[1:6, 1:4] OF INTEGER
Points[3, 2] ← 75
Q10.25 marks

The array Colours[1:50] already holds 50 colour names. Write pseudocode to input a colour and output how many times it appears in the array, or a suitable message if it does not appear.

Check my answermodel answer and marking points
✓ tested
OUTPUT "Enter a colour"
INPUT Colour
Count ← 0
FOR Index ← 1 TO 50
    IF Colours[Index] = Colour
      THEN
        Count ← Count + 1
    ENDIF
NEXT Index
IF Count = 0
  THEN
    OUTPUT Colour, " is not in the list"
  ELSE
    OUTPUT Colour, " appears ", Count, " times"
ENDIF
  • prompt + INPUT
  • Count set to 0
  • loop through all 50 elements
  • compare element with the input, add 1
  • both outputs
Q10.3Complete the algorithm5 marks

Complete this bubble sort so that Scores[1:20] is sorted into descending order.

Last ←  
REPEAT
    Swap ←  
    FOR Index ← 1 TO Last - 1
        IF Scores[Index]   Scores[Index + 1]
          THEN
            Temp ← Scores[Index]
            Scores[Index] ←  
            Scores[Index + 1] ← Temp
            Swap ← TRUE
        ENDIF
    NEXT Index
    Last ← Last - 1
UNTIL   OR Last = 1
Check my answermodel answer and marking points
  1. 20
  2. FALSE
  3. <
  4. Scores[Index + 1]
  5. NOT Swap
Completed ✓ tested
Last ← 20
REPEAT
    Swap ← FALSE
    FOR Index ← 1 TO Last - 1
        IF Scores[Index] < Scores[Index + 1]
          THEN
            Temp ← Scores[Index]
            Scores[Index] ← Scores[Index + 1]
            Scores[Index + 1] ← Temp
            Swap ← TRUE
        ENDIF
    NEXT Index
    Last ← Last - 1
UNTIL NOT Swap OR Last = 1
Q10.46 marks

The 2D array Sales[1:4, 1:12] holds the monthly sales of 4 shops for 12 months (row = shop, column = month). Write pseudocode to output the total sales of each shop, then the number of the shop with the highest total.

Check my answermodel answer and marking points
✓ tested
BestTotal ← -1
BestShop ← 0
FOR Shop ← 1 TO 4
    ShopTotal ← 0
    FOR Month ← 1 TO 12
        ShopTotal ← ShopTotal + Sales[Shop, Month]
    NEXT Month
    OUTPUT "Shop ", Shop, " total sales: ", ShopTotal
    IF ShopTotal > BestTotal
      THEN
        BestTotal ← ShopTotal
        BestShop ← Shop
    ENDIF
NEXT Shop
OUTPUT "Shop ", BestShop, " sold the most: ", BestTotal
  • nested loops: shops outside, months inside
  • shop total reset to 0 for each shop
  • add Sales[Shop, Month]
  • output each shop's total
  • track the highest total and its shop number
  • final output
11

File handling

Syllabus 8.3

Big ideaVariables forget everything when the program stops. A file remembers.

Data in variables and arrays is lost when the program ends. A file keeps it, so it can be used again later or by another program.

StatementDoes
OPENFILE "Scores.txt" FOR READopen to read from it
OPENFILE "Scores.txt" FOR WRITEcreate a new file (an existing one is overwritten)
READFILE "Scores.txt", Lineread the next line into a variable
WRITEFILE "Scores.txt", Linewrite a value as the next line
CLOSEFILE "Scores.txt"close it when finished
Write three lines, then read the first back ✓ tested
DECLARE StudentName : STRING
DECLARE Count : INTEGER
OPENFILE "Names.txt" FOR WRITE
FOR Count ← 1 TO 3
    OUTPUT "Enter a name"
    INPUT StudentName
    WRITEFILE "Names.txt", StudentName
NEXT Count
CLOSEFILE "Names.txt"

OPENFILE "Names.txt" FOR READ
READFILE "Names.txt", StudentName
OUTPUT "First name in the file: ", StudentName
CLOSEFILE "Names.txt"

Your turn

Q11.14 marks

Write pseudocode to input the names of 3 players and store them in a new text file Players.txt.

Check my answermodel answer and marking points
✓ tested
DECLARE PlayerName : STRING
DECLARE Count : INTEGER
OPENFILE "Players.txt" FOR WRITE
FOR Count ← 1 TO 3
    OUTPUT "Enter player name ", Count
    INPUT PlayerName
    WRITEFILE "Players.txt", PlayerName
NEXT Count
CLOSEFILE "Players.txt"
  • OPENFILE … FOR WRITE
  • loop 3 times with prompt + INPUT
  • WRITEFILE inside the loop
  • CLOSEFILE
Q11.24 marks

The file Message.txt holds one line of text. Write pseudocode to read it, output it in upper case, and output the number of characters it contains.

Check my answermodel answer and marking points
✓ tested
DECLARE Message : STRING
OPENFILE "Message.txt" FOR READ
READFILE "Message.txt", Message
CLOSEFILE "Message.txt"
OUTPUT UCASE(Message)
OUTPUT "Number of characters: ", LENGTH(Message)
  • open for READ
  • READFILE into a variable
  • UCASE output
  • LENGTH output (and close the file)
Q11.32 marks

Explain why a program might store data in a file instead of only in an array.

Check my answermodel answer and marking points

Data in an array is lost when the program closes (RAM). A file stores it permanently, so it can be loaded next time the program runs or used by another program.

12

Trace tables and finding errors

Syllabus 7.3 · 7.7 · 7.8

Big ideaA trace table is you pretending to be the computer, one line at a time. Slow is fast here.

A trace table records every change to every variable, and every output, as you run the algorithm by hand. Rules that earn the marks:

  1. One column per variable, plus OUTPUT.
  2. Go line by line. When a variable changes, write its new value in the next free cell of its column.
  3. Start a new row when a column you have already written in this row changes again.
  4. Copy outputs exactly, text included.
  5. Never write a value that has not changed; blank cells are fine.
Worked example: input 5, -3, 8, 2, 0
01Total ← 002Count ← 003INPUT Number04WHILE Number <> 0 DO05    IF Number > 006      THEN07        Total ← Total + Number08        Count ← Count + 109    ENDIF10    INPUT Number11ENDWHILE12OUTPUT Total / Count
NumberTotalCountOUTPUT
00
551
-3
8132
2153
05

Purpose: it outputs the average of the positive numbers entered, stopping at 0. (The -3 is ignored.) Output 5.

Your turn

Q12.1Trace table5 marks

Complete the trace table for the input data 4, 9, 2, 9, 7 and state the purpose of the algorithm.

01Max ← 002Position ← 003FOR Index ← 1 TO 504    INPUT Value05    IF Value > Max06      THEN07        Max ← Value08        Position ← Index09    ENDIF10NEXT Index11OUTPUT Position, " ", Max
IndexValueMaxPositionOUTPUT
Check my answermodel answer and marking points
IndexValueMaxPositionOUTPUT
00
1441
2992
32
49
572 9

Purpose: finds the largest value and the position where it first appears. Discussion point: why is Position 2 and not 4? (> is not >=, so the second 9 does not replace the first.)

Q12.2Trace table4 marks

Complete the trace table for the input 4073 and describe what the algorithm does.

01INPUT Number02Total ← 003WHILE Number > 0 DO04    Digit ← MOD(Number, 10)05    Total ← Total + Digit06    Number ← DIV(Number, 10)07ENDWHILE08OUTPUT Total
NumberDigitTotalOUTPUT
Check my answermodel answer and marking points
NumberDigitTotalOUTPUT
40730
33
407710
400
4414
014

It adds up the digits of a whole number (4 + 0 + 7 + 3 = 14).

Q12.3Find the errors4 marks

This algorithm should input 10 positive numbers and output their average and the largest number. There are four errors. Give the line number of each error and the corrected line.

01Total ← 002Largest ← 003FOR Count ← 1 TO 1004    INPUT Number05    Total ← Number06    IF Number < Largest07      THEN08        Largest ← Number09    ENDIF10NEXT Number11Average ← Total * 1012OUTPUT Average, " ", Largest
Check my answermodel answer and marking points
LineCorrection
05Total ← Total + Number
06IF Number > Largest
10NEXT Count
11Average ← Total / 10
Corrected ✓ tested
Total ← 0
Largest ← 0
FOR Count ← 1 TO 10
    INPUT Number
    Total ← Total + Number
    IF Number > Largest
      THEN
        Largest ← Number
    ENDIF
NEXT Count
Average ← Total / 10
OUTPUT Average, " ", Largest
13

The 15-mark scenario question

Last question on every Paper 2 · about 30 minutes

Big ideaThe big question looks scary, but it is the same patterns you already know, put together in order.

Students get an unseen situation (rainfall records, river pollution, sports results…) with named arrays and a bullet list of requirements. They can answer in pseudocode, Python, Visual Basic or Java. It is marked with two level tables and a best-fit mark:

Marked forMaxLevel bandsWhat lifts the mark
AO2: applying techniques91–3 · 4–6 · 7–9the right techniques used correctly: declarations, input, loops, selection, totalling, counting, max/min, rounding, arrays used with the given names
AO3: a working, complete solution61–2 · 3–4 · 5–6every requirement met, logical order, meaningful names, comments, clear output messages

A method students can follow every time

  1. Tick-list (3 min). Number every bullet in the question. These become R1, R2, R3 in your head.
  2. Data (2 min). List every array (use the exact names given), variable and constant. Declare them all.
  3. Write in blocks with a comment above each: declarations → input (with validation) → processing (totals, counts, max/min, averages) → output.
  4. Every INPUT gets a prompt; every OUTPUT gets a message. The question always asks for this.
  5. Check (3 min). Go down the tick-list; find the line of code that meets each bullet.

Worked example

Model answer (tested with 25 students and one invalid mark) ✓ tested
// ---- declarations ----
CONSTANT ClassSize ← 25
CONSTANT Tests ← 3
DECLARE StudentName : ARRAY[1:25] OF STRING
DECLARE Marks : ARRAY[1:25, 1:3] OF INTEGER
DECLARE Student : INTEGER
DECLARE Test : INTEGER
DECLARE StudentTotal : INTEGER
DECLARE Average : REAL
DECLARE Distinctions : INTEGER
DECLARE Passes : INTEGER
DECLARE Fails : INTEGER
DECLARE BestAverage : REAL
DECLARE BestStudent : STRING

// ---- R1: input every name and mark; range check each mark ----
FOR Student ← 1 TO ClassSize
    OUTPUT "Enter the name of student ", Student
    INPUT StudentName[Student]
    FOR Test ← 1 TO Tests
        OUTPUT "Enter the mark for test ", Test, " (0 to 100)"
        INPUT Marks[Student, Test]
        WHILE Marks[Student, Test] < 0 OR Marks[Student, Test] > 100 DO
            OUTPUT "Invalid mark. Enter a mark from 0 to 100"
            INPUT Marks[Student, Test]
        ENDWHILE
    NEXT Test
NEXT Student

// ---- R2 + R3: total, average and result for each student ----
Distinctions ← 0
Passes ← 0
Fails ← 0
BestAverage ← -1
FOR Student ← 1 TO ClassSize
    StudentTotal ← 0
    FOR Test ← 1 TO Tests
        StudentTotal ← StudentTotal + Marks[Student, Test]
    NEXT Test
    Average ← ROUND(StudentTotal / Tests, 1)
    OUTPUT StudentName[Student], " total: ", StudentTotal, " average: ", Average
    // decide and count the result
    IF Average >= 70
      THEN
        OUTPUT "Result: Distinction"
        Distinctions ← Distinctions + 1
      ELSE
        IF Average >= 40
          THEN
            OUTPUT "Result: Pass"
            Passes ← Passes + 1
          ELSE
            OUTPUT "Result: Fail"
            Fails ← Fails + 1
        ENDIF
    ENDIF
    // remember the highest average so far
    IF Average > BestAverage
      THEN
        BestAverage ← Average
        BestStudent ← StudentName[Student]
    ENDIF
NEXT Student

// ---- R3: class summary ----
OUTPUT "Distinctions: ", Distinctions, "  Passes: ", Passes, "  Fails: ", Fails
OUTPUT "Highest average: ", BestStudent, " with ", BestAverage
RequirementWhere it is met
R1 input + validationthe first nested FOR, with the WHILE range check
R2 total and averageStudentTotal reset per student; ROUND(…, 1) after the inner loop
R3 result + countsnested IF with three counters
R3 highest averageBestAverage / BestStudent updated with >
AO3 qualitycomments on every block, constants, meaningful names, a message on every input and output

Practice scenario (class or homework)

Q13.1Scenario15 marks
Check my answermodel answer and marking points
Model answer (tested: a double booking, row 9, seat 15) ✓ tested
// ---- declarations ----
CONSTANT Rows ← 8
CONSTANT SeatsPerRow ← 12
CONSTANT FrontPrice ← 6
CONSTANT BackPrice ← 9
DECLARE Booked : ARRAY[1:8, 1:12] OF BOOLEAN
DECLARE Row : INTEGER
DECLARE Seat : INTEGER
DECLARE SeatsBooked : INTEGER
DECLARE Takings : INTEGER
DECLARE RowCount : INTEGER
DECLARE BestRow : INTEGER
DECLARE BestCount : INTEGER

// ---- set every seat to free ----
FOR Row ← 1 TO Rows
    FOR Seat ← 1 TO SeatsPerRow
        Booked[Row, Seat] ← FALSE
    NEXT Seat
NEXT Row

// ---- take bookings until the row entered is 0 ----
SeatsBooked ← 0
Takings ← 0
OUTPUT "Enter the row number (1 to 8), or 0 to finish"
INPUT Row
WHILE Row <> 0 DO
    IF Row < 1 OR Row > Rows
      THEN
        OUTPUT "There is no row ", Row
      ELSE
        OUTPUT "Enter the seat number (1 to 12)"
        INPUT Seat
        WHILE Seat < 1 OR Seat > SeatsPerRow DO
            OUTPUT "Invalid seat. Enter a seat number from 1 to 12"
            INPUT Seat
        ENDWHILE
        IF Booked[Row, Seat] = TRUE
          THEN
            OUTPUT "Sorry, that seat is already booked"
          ELSE
            Booked[Row, Seat] ← TRUE
            SeatsBooked ← SeatsBooked + 1
            // price depends on the row
            IF Row <= 3
              THEN
                Takings ← Takings + FrontPrice
              ELSE
                Takings ← Takings + BackPrice
            ENDIF
            OUTPUT "Row ", Row, " seat ", Seat, " is booked"
        ENDIF
    ENDIF
    OUTPUT "Enter the row number (1 to 8), or 0 to finish"
    INPUT Row
ENDWHILE

// ---- summary ----
OUTPUT "Seats booked: ", SeatsBooked
OUTPUT "Seats free: ", Rows * SeatsPerRow - SeatsBooked
OUTPUT "Total takings: $", Takings

// ---- row with the most bookings ----
BestCount ← -1
BestRow ← 1
FOR Row ← 1 TO Rows
    RowCount ← 0
    FOR Seat ← 1 TO SeatsPerRow
        IF Booked[Row, Seat] = TRUE
          THEN
            RowCount ← RowCount + 1
        ENDIF
    NEXT Seat
    IF RowCount > BestCount
      THEN
        BestCount ← RowCount
        BestRow ← Row
    ENDIF
NEXT Row
OUTPUT "Row ", BestRow, " has the most seats booked (", BestCount, ")"
RequirementLook for
R1 set upnested loops set all 96 elements to FALSE
R2 bookingsWHILE with 0 as the rogue value; row and seat validated; already-booked check; booking, count and price by row
R3 summarybooked, free (96 − booked) and takings output with messages
R3 busiest rowcount per row reset to 0 for each row; max with its row number
AO3comments, constants for prices and sizes, declarations, prompts on every input

Second scenario for homework

Q13.2Scenario15 marks
Check my answermodel answer and marking points
Model answer (tested: two students, one invalid answer, lower-case END) ✓ tested
// ---- declarations (Key[1:10] is already filled) ----
DECLARE StudentName : STRING
DECLARE Answer : STRING
DECLARE Question : INTEGER
DECLARE Score : INTEGER
DECLARE Percentage : INTEGER
DECLARE Students : INTEGER
DECLARE ClassTotal : INTEGER
DECLARE BestScore : INTEGER
DECLARE BestName : STRING

Students ← 0
ClassTotal ← 0
BestScore ← -1
OUTPUT "Enter the student's name, or END to finish"
INPUT StudentName
WHILE UCASE(StudentName) <> "END" DO
    // ---- mark one student's 10 answers ----
    Score ← 0
    FOR Question ← 1 TO 10
        OUTPUT "Answer for question ", Question, " (A, B, C or D)"
        INPUT Answer
        Answer ← UCASE(Answer)
        WHILE Answer <> "A" AND Answer <> "B" AND Answer <> "C" AND Answer <> "D" DO
            OUTPUT "Invalid. Enter A, B, C or D"
            INPUT Answer
            Answer ← UCASE(Answer)
        ENDWHILE
        IF Answer = Key[Question]
          THEN
            Score ← Score + 1
        ENDIF
    NEXT Question
    Percentage ← ROUND(Score / 10 * 100, 0)
    OUTPUT StudentName, " scored ", Score, " out of 10 (", Percentage, "%)"
    // ---- class totals and best student ----
    Students ← Students + 1
    ClassTotal ← ClassTotal + Score
    IF Score > BestScore
      THEN
        BestScore ← Score
        BestName ← StudentName
    ENDIF
    OUTPUT "Enter the student's name, or END to finish"
    INPUT StudentName
ENDWHILE

// ---- summary ----
IF Students > 0
  THEN
    OUTPUT "Best student: ", BestName, " with ", BestScore
    OUTPUT "Class average: ", ROUND(ClassTotal / Students, 1), " out of 10"
  ELSE
    OUTPUT "No students were entered"
ENDIF
14

One-page reference card

Everything students must be able to write

Big ideaEverything on one page, for the last look before the exam.

For the last five minutes of revision, or the back of an exercise book.

Data
DECLARE Count : INTEGER
DECLARE List : ARRAY[1:10] OF STRING
DECLARE Grid : ARRAY[1:3, 1:3] OF CHAR
CONSTANT Rate ← 0.2
Count ← Count + 1
INPUT Name
OUTPUT "Total: ", Total
Selection
IF Mark >= 50
  THEN
    OUTPUT "Pass"
  ELSE
    OUTPUT "Fail"
ENDIF

CASE OF Choice
  1 : OUTPUT "Start"
  2 : OUTPUT "Stop"
  OTHERWISE OUTPUT "Error"
ENDCASE
Iteration
FOR I ← 1 TO 10 STEP 1
    OUTPUT I
NEXT I

WHILE Number <> 0 DO
    INPUT Number
ENDWHILE

REPEAT
    INPUT Age
UNTIL Age > 0
Subroutines
PROCEDURE Greet(Name : STRING)
    OUTPUT "Hello ", Name
ENDPROCEDURE
CALL Greet("Ali")

FUNCTION Square(N : INTEGER) RETURNS INTEGER
    RETURN N * N
ENDFUNCTION
X ← Square(4)
Library routines
LENGTH(Word)
SUBSTRING(Word, Start, Length)
UCASE(Word)    LCASE(Word)
MOD(17, 5)     DIV(17, 5)
ROUND(Value, 2)
RANDOM()
Files
OPENFILE "Data.txt" FOR WRITE
WRITEFILE "Data.txt", Line
CLOSEFILE "Data.txt"
OPENFILE "Data.txt" FOR READ
READFILE "Data.txt", Line
CLOSEFILE "Data.txt"

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