References only, not question text. Open Official paper ↗ where Cambridge publishes the paper,
or see the official Cambridge past-papers page; for other papers, ask your
school. “Paper 42” means Paper 4, variant 2.
Practice questions
Original questions written by HomiLabs in the style of the exam, with answers and mark schemes. They are not
Cambridge past paper questions and have not been reviewed by Cambridge. Try each one before opening the answer.
Q1String & built-in functions · Core · Paper 2 style · 5 marks
M1: Index values 1, 4, 7, 10 (loop ends as 13 > 11); M1: Result grows by one character each time; A1: correct Result values; A1: output BOIA.
(b) BLCITN
B1: positions 1, 3, 5, 7, 9, 11.
Q6String & built-in functions · Core · Paper 4 style · 6 marks
(a)Write a function title_case(name) that returns name with the first letter of every word in upper case and every other letter in lower case. Words are separated by spaces. Do not use the built-in method title() or capitalize().Test the function with "muhammad ali jinnah", "FATIMA JINNAH" and "allama iqbal" (two spaces) and show the output.[6]
Show answer
(a)Python model answer (Java or VB.NET also accepted):def title_case(name): result = "" start_of_word = True for ch in name: if ch == " ": result = result + ch start_of_word = True elif start_of_word: result = result + ch.upper() start_of_word = False else: result = result + ch.lower() return resultfor test in ["muhammad ali jinnah", "FATIMA JINNAH", "allama iqbal"]: print(repr(title_case(test)))Output:'Muhammad Ali Jinnah''Fatima Jinnah''Allama Iqbal'
1 mark each, max 6: function with parameter that returns a string; loop over every character; flag/test for start of word (after a space or at position 0); start letters converted to upper case; other letters converted to lower case; spaces kept (double space preserved); test calls with output shown.
Q7String & built-in functions · Standard · Paper 2 style · 6 marks
(a)Write pseudocode for the function CountVowels(Phrase : STRING) RETURNS INTEGER. The function returns the number of vowels (a, e, i, o, u, in either upper or lower case) in Phrase.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[5]
(b)State the value returned by CountVowels("Mohenjo-daro").[1]
Show answer
(a)FUNCTION CountVowels(Phrase : STRING) RETURNS INTEGER DECLARE Count, Index : INTEGER DECLARE ThisChar : STRING Count ← 0 FOR Index ← 1 TO LENGTH(Phrase) ThisChar ← TO_LOWER(MID(Phrase, Index, 1)) IF ThisChar = "a" OR ThisChar = "e" OR ThisChar = "i" OR ThisChar = "o" OR ThisChar = "u" THEN Count ← Count + 1 ENDIF NEXT Index RETURN CountENDFUNCTION
1 mark each, max 5: function header and end with RETURNS INTEGER; counter declared and initialised to 0 before the loop; loop from 1 to LENGTH(Phrase); extract one character with MID(Phrase, Index, 1); handles case (TO_LOWER/TO_UPPER or test both cases); full comparison with all five vowels (each comparison written in full, not 'ThisChar = "a" OR "e"'); increment count; RETURN Count (not OUTPUT).
(b) 5
B1: o, e, o, a, o = 5.
Q8String & built-in functions · Standard · Paper 2 style · 7 marks
(a)Write pseudocode for the function Reverse(InString : STRING) RETURNS STRING, which returns the characters of InString in reverse order. For example, Reverse("Ravi") returns "ivaR".You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[5]
(b)A programmer uses the function in the expression Reverse("level") = "level". State the value of the expression and what it shows about the word.[2]
Show answer
(a)FUNCTION Reverse(InString : STRING) RETURNS STRING DECLARE Result : STRING DECLARE Index : INTEGER Result ← "" FOR Index ← LENGTH(InString) TO 1 STEP -1 Result ← Result & MID(InString, Index, 1) NEXT Index RETURN ResultENDFUNCTION
1 mark each: header/footer with parameter and RETURNS STRING; Result initialised to empty string; loop through every character (either backwards with STEP -1, or forwards building Result ← MID(...) & Result); correct use of MID to extract one character; concatenation in the correct order; RETURN Result. Max 5.
(b) TRUE; the word is a palindrome (reads the same forwards and backwards).
B1: TRUE. B1: palindrome.
Q9String & built-in functions · Standard · Paper 2 style · 7 marks
(a)Write pseudocode for the function GetInitials(FullName : STRING) RETURNS STRING.FullName contains one or more names separated by single spaces, with no space at the start or end. The function returns the first letter of each name in upper case. For example, GetInitials("ali raza khan") returns "ARK".You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[6]
(b)State the value returned by GetInitials("Benazir Bhutto").[1]
Show answer
(a)FUNCTION GetInitials(FullName : STRING) RETURNS STRING DECLARE Initials : STRING DECLARE Index : INTEGER Initials ← TO_UPPER(LEFT(FullName, 1)) FOR Index ← 2 TO LENGTH(FullName) IF MID(FullName, Index - 1, 1) = " " THEN Initials ← Initials & TO_UPPER(MID(FullName, Index, 1)) ENDIF NEXT Index RETURN InitialsENDFUNCTION
1 mark each: header with STRING parameter and return type; first character taken as first initial; loop through remaining characters; detect a space (character before is a space, or current is a space then take the next); add the character after the space; convert to upper case; RETURN the result. Max 6.
(b) "BB"
B1.
Q10String & built-in functions · Standard · Paper 2 style · 7 marks
(a)Write pseudocode for the function CountWords(Sentence : STRING) RETURNS INTEGER.Words are separated by one or more spaces, and Sentence may start or end with spaces. For example, CountWords(" The Indus is long ") returns 4.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[6]
(b)Explain why simply counting the spaces and adding 1 does not give the correct result for the example.[1]
Show answer
(a)FUNCTION CountWords(Sentence : STRING) RETURNS INTEGER DECLARE Count, Index : INTEGER DECLARE Previous, ThisChar : CHAR Count ← 0 Previous ← ' ' FOR Index ← 1 TO LENGTH(Sentence) ThisChar ← MID(Sentence, Index, 1) IF ThisChar <> ' ' AND Previous = ' ' THEN Count ← Count + 1 ENDIF Previous ← ThisChar NEXT Index RETURN CountENDFUNCTION
1 mark each, max 6: Count initialised to 0; loop through all characters; extract each character; a word is counted at the start of a word (non-space after a space, or at position 1); multiple / leading / trailing spaces do not add extra words; previous character updated each iteration; RETURN Count. Counting spaces + 1 scores max 3 as it fails the given example.
(b) The example has 7 spaces (including leading, double and trailing spaces), which would give 8, not 4.
B1: extra spaces would be counted (7 + 1 = 8 ≠ 4).
Q11String & built-in functions · Standard · Paper 2 style · 8 marks
A sports club in Karachi creates usernames for new members.
(a)Write pseudocode for the function MakeUsername(FirstName : STRING, Surname : STRING, YearJoined : INTEGER) RETURNS STRING.The username is made of:• the first three letters of Surname in upper case• the last two digits of YearJoined, always as two characters (2007 gives "07")• the number of characters in FirstName.You may assume Surname has at least three letters.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[6]
(b)State the usernames produced for:(i) "Ayesha", "siddiqui", 2025(ii) "Omar", "khan", 2007[2]
1 mark each: header with three parameters and return type; TO_UPPER(LEFT(Surname, 3)); last two digits using MOD(YearJoined, 100) (or RIGHT(NUM_TO_STR(YearJoined), 2), which also earns the next mark); leading zero added when needed; NUM_TO_STR(LENGTH(FirstName)); concatenated in the correct order and returned.
(b) (i) "SID256" (ii) "KHA074"
1 mark each.
Q12String & built-in functions · Standard · Paper 2 style · 6 marks
(a)Write pseudocode for the function BinToDenary(BinString : STRING) RETURNS INTEGER. BinString contains only the characters '0' and '1' (up to 16 of them). The function returns the denary value. For example, BinToDenary("101101") returns 45.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[5]
(b)State the value returned by BinToDenary("11111111").[1]
Show answer
(a)FUNCTION BinToDenary(BinString : STRING) RETURNS INTEGER DECLARE Value, Index : INTEGER Value ← 0 FOR Index ← 1 TO LENGTH(BinString) Value ← Value * 2 IF MID(BinString, Index, 1) = '1' THEN Value ← Value + 1 ENDIF NEXT Index RETURN ValueENDFUNCTION
1 mark each: Value initialised to 0; loop over every character; extract character with MID; correct place-value method (double then add, or add place value that doubles from the right); RETURN Value. Max 5.
(b) 255
B1.
Q13String & built-in functions · Standard · Paper 2 style · 6 marks
(a)Evaluate MONTH(SETDATE(14, 8, 1947)).[1]
(b)Write pseudocode for the function FormatDate(ThisDate : DATE) RETURNS STRING, which returns the date as a string in the form DD/MM/YYYY, with a leading zero for days and months below 10. For example, the date 5 March 2026 is returned as "05/03/2026".You may also use the functions DAY(ThisDate), MONTH(ThisDate) and YEAR(ThisDate), which return integers.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[5]
1 mark each: uses DAY, MONTH and YEAR; converts each to a string with NUM_TO_STR; adds leading zero to day when < 10; adds leading zero to month when < 10; concatenates with '/' separators in the correct order and RETURNs the string.
Q14String & built-in functions · Standard · Paper 4 style · 8 marks
A bank in Lahore checks new online-banking passwords. A password scores one point for each rule it meets:• it has at least 8 characters• it contains at least one upper-case letter• it contains at least one lower-case letter• it contains at least one digit.A score of 4 is "Strong", 2 or 3 is "Medium", and 0 or 1 is "Weak".
(a)Write a program that:• defines a function password_strength(password) that returns "Strong", "Medium" or "Weak" using the scoring rules above, examining the string one character at a time (do not use built-in methods such as isupper())• tests the function with each of these passwords and prints the password and its result:Karachi2026, karachi, PESHAWAR, abc, Abc12, 12345678Save your program, run it, and show the output as evidence.[8]
Show answer
(a)Python model answer (Java or VB.NET also accepted):def password_strength(password): has_upper = False has_lower = False has_digit = False for ch in password: if "A" <= ch <= "Z": has_upper = True elif "a" <= ch <= "z": has_lower = True elif "0" <= ch <= "9": has_digit = True score = 0 if len(password) >= 8: score += 1 if has_upper: score += 1 if has_lower: score += 1 if has_digit: score += 1 if score == 4: return "Strong" elif score >= 2: return "Medium" else: return "Weak"for test in ["Karachi2026", "karachi", "PESHAWAR", "abc", "Abc12", "12345678"]: print(test, password_strength(test))Output:Karachi2026 Strongkarachi WeakPESHAWAR Mediumabc WeakAbc12 Medium12345678 Medium
1 mark each, max 8: function header with parameter; loop over every character; detects upper case; detects lower case; detects digit; length test ≥ 8; score calculated correctly (one point per rule, not per character); returns correct category for 4, 2–3 and 0–1 points; returns (not prints) the result inside the function; test calls for all six passwords with output; screenshot/evidence of the output matching the expected results.
Q15String & built-in functions · Challenge · Paper 2 style · 7 marks
(a)Write pseudocode for the function IsPalindrome(Text : STRING) RETURNS BOOLEAN.The function returns TRUE if Text reads the same forwards and backwards when spaces are ignored and upper and lower case are treated as the same. For example, IsPalindrome("Never odd or even") returns TRUE and IsPalindrome("Lahore") returns FALSE.Do not use a separate reverse function.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[7]
Show answer
(a)FUNCTION IsPalindrome(Text : STRING) RETURNS BOOLEAN DECLARE Clean : STRING DECLARE Index, Last : INTEGER DECLARE Match : BOOLEAN Clean ← "" FOR Index ← 1 TO LENGTH(Text) IF MID(Text, Index, 1) <> " " THEN Clean ← Clean & TO_UPPER(MID(Text, Index, 1)) ENDIF NEXT Index Match ← TRUE Index ← 1 Last ← LENGTH(Clean) WHILE Index < Last AND Match = TRUE IF MID(Clean, Index, 1) <> MID(Clean, Last, 1) THEN Match ← FALSE ENDIF Index ← Index + 1 Last ← Last - 1 ENDWHILE RETURN MatchENDFUNCTION
1 mark each, max 7: correct header with BOOLEAN return; loop through Text; removes/skips spaces; converts case consistently; builds cleaned string; compares characters from both ends (first with last, moving inwards) or builds a reversed copy in-line; loop stops at the middle / when a mismatch found; sets result FALSE on mismatch; RETURN of a Boolean value in all cases.
Q16String & built-in functions · Challenge · Paper 2 style · 10 marks
A car park in Islamabad records vehicle registrations in this format:• three upper-case letters, then• a hyphen '-', then• three or four digits.For example, "LEA-1234" and "ICT-567" are valid; "LE-12345" is not.
(a)Write pseudocode for the function ValidReg(Reg : STRING) RETURNS BOOLEAN that returns TRUE only if Reg is in the correct format.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[7]
(b)Give the value returned by ValidReg for each string.(i) "lea-1234" (ii) "ICT-567" (iii) "LEA 1234"[3]
Show answer
(a)FUNCTION ValidReg(Reg : STRING) RETURNS BOOLEAN DECLARE Index : INTEGER DECLARE ThisChar : CHAR DECLARE Valid : BOOLEAN Valid ← TRUE IF LENGTH(Reg) <> 7 AND LENGTH(Reg) <> 8 THEN Valid ← FALSE ELSE FOR Index ← 1 TO 3 ThisChar ← MID(Reg, Index, 1) IF ThisChar < 'A' OR ThisChar > 'Z' THEN Valid ← FALSE ENDIF NEXT Index IF MID(Reg, 4, 1) <> '-' THEN Valid ← FALSE ENDIF FOR Index ← 5 TO LENGTH(Reg) ThisChar ← MID(Reg, Index, 1) IF ThisChar < '0' OR ThisChar > '9' THEN Valid ← FALSE ENDIF NEXT Index ENDIF RETURN ValidENDFUNCTION
1 mark each, max 7: check length is 7 or 8; length check done before characters are accessed; loop over the first three characters; test each is in range 'A' to 'Z'; test fourth character is '-'; loop from 5 to LENGTH(Reg); test each is a digit '0'–'9' (or IS_NUM on the substring, provided it rejects signs/decimal points); return TRUE only if all tests pass, FALSE otherwise.
(b) (i) FALSE (ii) TRUE (iii) FALSE
1 mark each. (i) lower-case letters; (iii) space instead of hyphen.
Q17String & built-in functions · Challenge · Paper 2 style · 8 marks
(a)Write pseudocode for the function Encrypt(Message : STRING, Shift : INTEGER) RETURNS STRING.Each upper-case letter in Message is replaced by the letter Shift places later in the alphabet, wrapping round from 'Z' back to 'A'. All other characters are unchanged. Shift is between 1 and 25. ASC('A') returns 65.You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[7]
(b)State the value returned by Encrypt("ZOO 7", 3).[1]
Show answer
(a)FUNCTION Encrypt(Message : STRING, Shift : INTEGER) RETURNS STRING DECLARE Result : STRING DECLARE ThisChar : CHAR DECLARE Index, Code : INTEGER Result ← "" FOR Index ← 1 TO LENGTH(Message) ThisChar ← MID(Message, Index, 1) IF ThisChar >= 'A' AND ThisChar <= 'Z' THEN Code ← MOD(ASC(ThisChar) - 65 + Shift, 26) + 65 Result ← Result & CHR(Code) ELSE Result ← Result & ThisChar ENDIF NEXT Index RETURN ResultENDFUNCTION
1 mark each, max 7: header with two parameters and STRING return; result initialised; loop through each character; extract with MID; test for upper-case letter; use ASC to get code and add Shift; wrap round correctly (MOD 26, or IF Code > 90 THEN Code ← Code − 26); convert back with CHR and concatenate; non-letters copied unchanged; RETURN result.
(b) "CRR 7"
B1: Z→C (wraps), O→R, O→R, space and 7 unchanged.
Q18String & built-in functions · Challenge · Paper 2 style · 9 marks
(a)Write pseudocode for the function ValidEmail(Address : STRING) RETURNS BOOLEAN. The function returns TRUE only if all of these rules are met:• Address contains exactly one '@' character, which is not the first character• at least one '.' appears after the '@'• no '.' appears immediately after the '@'• the last character is not '.'You may use the pseudocode functions LEFT, RIGHT, MID, LENGTH, TO_UPPER, TO_LOWER, NUM_TO_STR, STR_TO_NUM, IS_NUM, ASC, CHR, INT, MOD and DIV.[7]
(b)Give one example of a string that passes this check but is still not a working email address, and state why validation cannot prevent this.[2]
Show answer
(a)FUNCTION ValidEmail(Address : STRING) RETURNS BOOLEAN DECLARE Index, AtCount, AtPos : INTEGER DECLARE DotAfter : BOOLEAN DECLARE ThisChar : CHAR AtCount ← 0 AtPos ← 0 DotAfter ← FALSE FOR Index ← 1 TO LENGTH(Address) ThisChar ← MID(Address, Index, 1) IF ThisChar = '@' THEN AtCount ← AtCount + 1 AtPos ← Index ENDIF IF ThisChar = '.' AND AtPos > 0 AND Index > AtPos + 1 THEN DotAfter ← TRUE ENDIF NEXT Index IF AtCount <> 1 OR AtPos = 1 OR DotAfter = FALSE THEN RETURN FALSE ENDIF IF MID(Address, AtPos + 1, 1) = '.' OR RIGHT(Address, 1) = '.' THEN RETURN FALSE ENDIF RETURN TRUEENDFUNCTION
1 mark each, max 7: loop through each character with MID; count '@' characters; record position of '@'; reject if count not exactly 1; reject '@' at position 1; detect a '.' after the '@'; reject '.' directly after '@'; reject final '.'; returns BOOLEAN in every path. (Note: AtPos + 1 cannot exceed the length when a dot after '@' exists, as that dot is at least two places after '@'.)
(b) e.g. "zainab@notreal.xyz" – it has the correct format, but validation only checks format/reasonableness, not whether the address actually exists.
B1 suitable example; B1 validation checks rules/format, not correctness/existence.
Q19String & built-in functions · Challenge · Paper 2 style · 8 marks
The function FindSpace(Text : STRING) RETURNS INTEGER should return the position of the first space in Text, or −1 if there is no space. It contains four errors.01 FUNCTION FindSpace(Text : STRING) RETURNS INTEGER02 DECLARE Index, Position : INTEGER03 Position ← 004 Index ← 105 WHILE Index < LENGTH(Text) AND Position = -106 IF MID(Text, 1, Index) = " " THEN07 Position ← Index08 ENDIF09 Index ← Index + 110 ENDWHILE11 RETURN Index12 ENDFUNCTION
(a)Identify the line number of each of the four errors in the function and write the corrected line.[8]
Show answer
(a)Line 03: Position ← -1Line 05: WHILE Index <= LENGTH(Text) AND Position = -1Line 06: IF MID(Text, Index, 1) = " " THENLine 11: RETURN Position
For each error: B1 line number, B1 correct replacement. Line 03 – Position must start at −1, otherwise the loop never runs and 0 would be wrong for 'not found'. Line 05 – '<' misses the last character. Line 06 – MID parameters wrong: must take 1 character at position Index. Line 11 – must return Position, not Index.
Q20String & built-in functions · Challenge · Paper 4 style · 10 marks
(a)Write a program with:• a function encode(text) that returns the run-length encoded form of text, where each run is written as its length followed by the character; for example encode("WWWWBBBR") returns "4W3B1R"• a function decode(code) that reverses the process; runs may be longer than 9 characters, for example "12A1B"• test code that encodes and then decodes each of "WWWWBBBR", "AAAAAAAAAAAAB", "XYZ" and the empty string, printing the original, encoded and decoded strings and whether the decoded string matches the original.You may assume the text contains no digit characters.Run the program and show the output as evidence.[10]
Show answer
(a)Python model answer (Java or VB.NET also accepted):def encode(text): if text == "": return "" result = "" count = 1 for i in range(1, len(text)): if text[i] == text[i - 1]: count += 1 else: result = result + str(count) + text[i - 1] count = 1 result = result + str(count) + text[-1] return resultdef decode(code): result = "" number = "" for ch in code: if "0" <= ch <= "9": number = number + ch else: result = result + ch * int(number) number = "" return resultfor test in ["WWWWBBBR", "AAAAAAAAAAAAB", "XYZ", ""]: e = encode(test) print(repr(test), "->", repr(e), "->", repr(decode(e)), decode(e) == test)Output:'WWWWBBBR' -> '4W3B1R' -> 'WWWWBBBR' True'AAAAAAAAAAAAB' -> '12A1B' -> 'AAAAAAAAAAAAB' True'XYZ' -> '1X1Y1Z' -> 'XYZ' True'' -> '' -> '' True
encode (max 5): handles empty string; counts consecutive equal characters; writes count (converted to string) then character when the run ends; final run written after the loop; returns the string. decode (max 4): builds the number from one or more digits; when a letter is met repeats it int(number) times; resets the number; returns the string. Testing (1): all four tests run with output shown.
Q21Constructs & expressions · Core · Paper 2 style · 4 marks
The variables have these values: A ← 7, B ← 3, Flag ← FALSE
(a)Evaluate each expression.(i) DIV(A, B) * B + MOD(A, B)(ii) A / B > 2(iii) NOT Flag AND (A < B OR B = 3)(iv) MOD(A + B, 4)[4]
Show answer
(a) (i) 7 (ii) TRUE (iii) TRUE (iv) 2
1 mark each. (i) 2 × 3 + 1. (ii) 7 / 3 = 2.33… > 2. (iii) NOT FALSE = TRUE; (FALSE OR TRUE) = TRUE; TRUE AND TRUE. (iv) 10 MOD 4.
Q22Constructs & expressions · Standard · Paper 2 style · 5 marks
A canteen app at a university in Peshawar uses this algorithm:IF Choice = 'T' THEN Price ← 60ELSE IF Choice = 'S' THEN Price ← 120 ELSE IF Choice = 'B' THEN Price ← 250 ELSE OUTPUT "Invalid choice" Price ← 0 ENDIF ENDIFENDIF
(a)Rewrite the algorithm using a CASE structure instead of nested IF statements.[4]
1 mark each: CASE OF Choice … ENDCASE; correct three cases with values; OTHERWISE clause containing both statements; correct syntax (colons, character literals).
(b) It is easier to read and maintain (and to add new choices) than deeply nested IF statements.
B1: clearer / easier to add options / fewer ENDIFs to match.
Q23Constructs & expressions · Standard · Paper 2 style · 6 marks
Total ← 0REPEAT INPUT Number Total ← Total + NumberUNTIL Total > 100OUTPUT Total
(a)Rewrite the algorithm using a pre-condition (WHILE) loop so that it gives exactly the same result for all inputs.[3]
(b)Explain the difference between a pre-condition loop and a post-condition loop.[2]
(c)The input values are 45, 30, 20, 10. State the output.[1]
Show answer
(a)Total ← 0WHILE Total <= 100 INPUT Number Total ← Total + NumberENDWHILEOUTPUT Total
1 mark each: Total initialised before the loop; WHILE … ENDWHILE structure with INPUT and addition inside; condition is the opposite of UNTIL condition: Total <= 100 (accept NOT (Total > 100)).
(b) A pre-condition loop tests its condition before each iteration, so the body may not run at all; a post-condition loop tests after each iteration, so the body always runs at least once.
1 mark each.
(c) 105
B1: 45, 75, 95, 105 – loop stops when Total > 100.
Q24Constructs & expressions · Challenge · Paper 2 style · 7 marks
Count ← 0FOR Row ← 1 TO 4 FOR Col ← Row TO 4 IF MOD(Row + Col, 2) = 0 THEN Count ← Count + Col ENDIF NEXT ColNEXT RowOUTPUT Count
(a)State the value that is output.[4]
(b)State how many times the IF statement is executed in total.[1]
(c)The inner loop is changed to FOR Col ← 1 TO Row. State the new output.[2]
M1: pairs with Row + Col even and Col ≤ Row: (1,1), (2,2), (3,1), (3,3), (4,2), (4,4); A1: 1 + 2 + 1 + 3 + 2 + 4 = 13.
Q25Constructs & expressions · Challenge · Paper 2 style · 7 marks
A sports academy in Sialkot registers children for coaching.
(a)Write pseudocode to:• input an age, repeating the input until it is a whole number between 5 and 18 inclusive, with an error message after each invalid entry• then output "Junior" for ages 5 to 11 and "Senior" for ages 12 to 18.You may assume the user always types a number, but it may not be a whole number. You may use the function INT.[5]
(b)Explain why a count-controlled (FOR) loop is not suitable for the validation.[2]
Show answer
(a)DECLARE Age : REALINPUT AgeWHILE Age < 5 OR Age > 18 OR Age <> INT(Age) OUTPUT "Age must be a whole number from 5 to 18" INPUT AgeENDWHILEIF Age <= 11 THEN OUTPUT "Junior"ELSE OUTPUT "Senior"ENDIF
1 mark each: input inside a conditional loop; range test with correct inclusive boundaries; whole-number test (Age = INT(Age)); error message only for invalid entries; correct selection for Junior/Senior after the loop. A REPEAT…UNTIL version with the error message inside an IF is equally acceptable.
(b) The number of attempts the user will need is not known in advance; the loop must continue until a valid value is entered, so a condition-controlled loop is needed.
1 mark each: number of iterations unknown; must stop on a condition (valid input).
Q26Procedures, functions & parameters · Core · Paper 2 style · 4 marks
(a)Explain the difference between a procedure and a function.[2]
(b)Explain the difference between passing a parameter by value and by reference.[2]
Show answer
(a) A function returns a single value to the point where it was called and is used in an expression; a procedure does not return a value through its name and is called as a statement using CALL.
1 mark each: function returns a value (used in an expression / assignment); procedure called with CALL as a statement / does not return a value.
(b) By value, a copy of the value is passed, so changes inside the subroutine do not affect the original variable. By reference, the address of the variable is passed, so changes inside the subroutine change the original variable.
1 mark each.
Q27Procedures, functions & parameters · Standard · Paper 2 style · 6 marks
PROCEDURE Adjust(BYVAL X : INTEGER, BYREF Y : INTEGER) X ← X * 2 Y ← Y + X OUTPUT X, " ", YENDPROCEDUREMain program:A ← 5B ← 3CALL Adjust(A, B)OUTPUT A, " ", BCALL Adjust(B, A)OUTPUT A, " ", B
(a)State the four lines of output produced by the main program.[4]
(b)Explain why the value of A did not change after the first call but did change after the second call.[2]
Show answer
(a)10 135 1326 3131 13
1 mark per line. Line 1: X = 10, B becomes 3 + 10. Line 2: A unchanged (by value), B changed (by reference). Line 3: X = 13 × 2 = 26; A becomes 5 + 26 = 31. Line 4: A = 31, B = 13.
(b) In the first call A is passed to X by value, so only a copy is changed. In the second call A is passed to Y, which is by reference, so the changes to Y change A.
1 mark each.
Q28Procedures, functions & parameters · Standard · Paper 2 style · 6 marks
A clothing store in Hyderabad is writing a program for its loyalty scheme.
(a)Write the pseudocode header for a function CalcDiscount that takes the price of an item (a real number) and the number of years a customer has been a member (an integer) and returns the discount as a real number.[2]
(b)Write the pseudocode header for a procedure UpdateStock that takes an item code (a string) by value and the quantity in stock (an integer) by reference.[2]
(c)Write one pseudocode statement that calls CalcDiscount for a price of 2500.00 and 3 years, and subtracts the result from the variable Total.[2]
Show answer
(a) FUNCTION CalcDiscount(Price : REAL, Years : INTEGER) RETURNS REAL
B1: FUNCTION name with two parameters and data types; B1: RETURNS REAL.
B1: PROCEDURE header with both parameters typed; B1: BYVAL and BYREF used correctly.
(c) Total ← Total - CalcDiscount(2500.00, 3)
B1: function call used in an expression (not with CALL); B1: correct arguments and assignment.
Q29Procedures, functions & parameters · Challenge · Paper 2 style · 8 marks
A global array Scores : ARRAY[1:50] OF INTEGER holds the scores of 50 players in a cricket league in Lahore. Every element contains a value.
(a)Write pseudocode for the procedure FindRange(BYREF Lowest : INTEGER, BYREF Highest : INTEGER), which finds the lowest and highest values in the global array Scores and passes them back through its parameters.[5]
(b)Write pseudocode statements in the main program to call FindRange and output the difference between the highest and lowest scores.[2]
(c)Explain why FindRange is written as a procedure with BYREF parameters rather than as a function.[1]
Show answer
(a)PROCEDURE FindRange(BYREF Lowest : INTEGER, BYREF Highest : INTEGER) DECLARE Index : INTEGER Lowest ← Scores[1] Highest ← Scores[1] FOR Index ← 2 TO 50 IF Scores[Index] < Lowest THEN Lowest ← Scores[Index] ENDIF IF Scores[Index] > Highest THEN Highest ← Scores[Index] ENDIF NEXT IndexENDPROCEDURE
1 mark each: header and ENDPROCEDURE; initialise both to Scores[1] (not 0 or a fixed guess); loop through remaining elements; correct comparison and update for Lowest; correct comparison and update for Highest; no RETURN / OUTPUT used to pass values back. Max 5.
(b)DECLARE Low, High : INTEGERCALL FindRange(Low, High)OUTPUT High - Low
B1: CALL with two variables (not literals); B1: output High − Low after the call.
(c) A function can return only one value, but two values (lowest and highest) must be passed back.
B1.
Q30Procedures, functions & parameters · Challenge · Paper 4 style · 9 marks
An electricity company in a fictional city uses this monthly tariff:• the first 100 units cost Rs 10 per unit• the next 100 units (101 to 200) cost Rs 15 per unit• every unit above 200 costs Rs 22 per unit• a fixed charge of Rs 75 is added to every bill.
(a)Write a program that:• defines a function calc_bill(units) that returns the total bill in rupees using the tariff above• defines a function get_units() that asks the user for the units used, repeating until a whole number of 0 or more is entered, and returns it as an integer• tests calc_bill with 0, 100, 101, 150, 200 and 250 units, printing each result• then calls get_units() and prints the bill for the value entered.Run the program, entering abc, then -5, then 320, and show the output as evidence.[9]
Show answer
(a)Python model answer (Java or VB.NET also accepted):FIXED_CHARGE = 75def calc_bill(units): if units <= 100: energy = units * 10 elif units <= 200: energy = 100 * 10 + (units - 100) * 15 else: energy = 100 * 10 + 100 * 15 + (units - 200) * 22 return energy + FIXED_CHARGEdef get_units(): valid = False while not valid: entry = input("Enter units used: ") if entry.isdigit(): units = int(entry) valid = True else: print("Units must be a whole number of 0 or more") return unitsfor u in [0, 100, 101, 150, 200, 250]: print(u, calc_bill(u))units = get_units()print("Bill: Rs", calc_bill(units))Output:0 75100 1075101 1090150 1825200 2575250 3675Enter units used: abcUnits must be a whole number of 0 or moreEnter units used: -5Units must be a whole number of 0 or moreEnter units used: 320Bill: Rs 5215
calc_bill (max 4): parameter used (not input inside the function); correct first band; correct second band with 100 × 10 plus the excess; correct third band; fixed charge added and value returned. get_units (max 3): loop until valid; rejects non-numeric and negative entries with a message; returns an integer. Testing (max 2): six test values with correct outputs (75, 1075, 1090, 1825, 2575, 3675); run with abc, −5, 320 giving Rs 5215.
Similar questions
Questions that test the same subtopic in different years, grouped so you can work on one skill at a time.
References only: find each question in its paper (official link where available, otherwise through your school).