Computer Science
Algorithms, programming and logic — Paper 2
- 1.
Write pseudocode that repeatedly inputs a test score until the value is between 0 and 100 inclusive, then outputs ‘valid’. Use a post-test or pre-test loop.
[4 marks] · no calculatorWorked explanation
- Pseudocode, assuming numeric input: REPEAT INPUT Score UNTIL Score >= 0 AND Score <= 100 OUTPUT "valid"
- Trace inputs -1,101,0: the until condition is false, false, true, so only after 0 is accepted does output occur. A pre-test version instead repeats while Score < 0 OR Score > 100 and must read another score inside the loop.
Common mistake: Score < 0 AND Score > 100 can never be true, so it does not repeat for invalid values.
Marking points
- Inputs a score before or within a suitable loop.
- Tests both lower and upper bounds correctly.
- Repeats while the score is outside 0 to 100, with correct Boolean logic.
- Outputs the valid message only after the loop terminates.
Examiner tip: For an invalid value use score < 0 OR score > 100; using AND makes the condition impossible.
- 2.
A delivery program accepts whole-number parcel weights from 1 to 20 kg inclusive, with a price-band change at 10 kg. Give test data and its purpose for each category: normal, extreme, boundary and invalid. For the boundary category give an adjacent accepted/rejected pair.
[4 marks] · no calculatorWorked explanation
- Normal: 5 kg, accepted to test an ordinary parcel. Extreme: 20 kg, accepted at the largest allowed whole-number weight.
- Boundary: 20 and 21 kg should be accepted and rejected respectively, checking the adjacent valid/invalid limit. Invalid: -2 kg should be rejected. Also test 9,10,11 kg for the separate price-band transition; the prompt does not supply prices, so no prices can be invented.
Common mistake: An extreme accepted limit is not an arbitrarily huge invalid stress-test value.
Marking points
- Gives a normal accepted value away from the limits, such as 5 kg, to check ordinary processing.
- Gives an extreme valid input, 1 kg or 20 kg, to check an acceptance limit.
- Gives an adjacent accepted/rejected boundary pair, such as 0 and 1 kg or 20 and 21 kg, explaining that the acceptance boundary is tested.
- Gives invalid data, such as -2 kg or nonnumeric text, to check rejection.
Examiner tip: For Cambridge 0478, extreme data is the smallest or largest accepted value; boundary data includes the limit and the adjacent rejected value. Do not confuse extreme input with an arbitrary high stress-test value.
- 3.
Write pseudocode to find and output the largest value in an array of 10 integers called Scores.
[4 marks] · no calculatorWorked explanation
- Using indices 1-10: Largest <- Scores[1] FOR i <- 2 TO 10 IF Scores[i] > Largest THEN Largest <- Scores[i] ENDIF NEXT i OUTPUT Largest
- Each iteration preserves the invariant that Largest is the greatest value seen. An illustrative prefix [-4,-7,-2] updates Largest as -4,-4,-2, showing why starting at zero would fail an all-negative array.
Common mistake: Initialising to zero can output a value not present when every score is negative.
Marking points
- Declares a variable to hold the largest value, initialised to the first array element.
- Uses a loop to traverse the remaining elements of the array.
- Compares each element to the current largest value and updates it when a bigger value is found.
- Outputs the largest value after the loop ends.
Examiner tip: Initialise the 'largest' variable with the first element, not zero — scores could be negative or the array could contain only small positive values.
- 4.
The list [5, 2, 8, 1] is sorted into ascending order using bubble sort, comparing adjacent pairs from left to right. State the list after the first full pass.
[3 marks] · no calculatorWorked explanation
- Left-to-right comparisons: [5,2,8,1] -> swap 5,2 -> [2,5,8,1]; compare 5,8, no swap; swap 8,1 -> [2,5,1,8].
- The first full pass leaves [2,5,1,8], with the largest at the right but the rest not yet sorted. Executable trace: `a=[5,2,8,1]` then `for i in range(3):` followed by `if a[i]>a[i+1]: a[i],a[i+1]=a[i+1],a[i]` as its nested body.
Common mistake: Reporting [1,2,5,8] gives the finished sort rather than the first pass.
Marking points
- Compares 5 and 2, swaps them to give [2, 5, 8, 1].
- Compares 5 and 8, no swap needed, giving [2, 5, 8, 1].
- Compares 8 and 1, swaps them to give the final first-pass result [2, 5, 1, 8].
Examiner tip: A bubble sort compares each adjacent pair in turn during a pass, swapping whenever the left value is greater than the right.
- 5.
A list of 1,000 names is already sorted alphabetically. Which search algorithm will generally find a specific name fastest? A Linear search B Binary search C Bubble sort D Insertion sort
[1 mark] · no calculatorCourse scope: Optional enrichment
Worked explanation
- Select B, binary search: compare the target with the middle name and discard the half that alphabetical order rules out.
- The remaining candidate counts are at most about 1000,500,250,125,63,32,16,8,4,2,1, requiring about ten comparisons rather than up to 1000 linear checks. Bubble and insertion are sorting methods, not searches.
Common mistake: Binary search's elimination step is unjustified if the names are not sorted.
Marking points
- Selects B: binary search repeatedly halves a sorted list, finding items far faster than checking each one in turn.
Examiner tip: Binary search requires the list to already be sorted; it cannot be used correctly on unsorted data.
- 6.
Write pseudocode using nested IF statements that outputs a grade for a given Score: 'A' if the score is 90 or above, 'B' if it is 75 or above but below 90, and 'C' otherwise.
[3 marks] · no calculatorWorked explanation
- Nested pseudocode: IF Score >= 90 THEN OUTPUT "A" ELSE IF Score >= 75 THEN OUTPUT "B" ELSE OUTPUT "C" ENDIF ENDIF
- Trace 90 -> A; 89 -> first false, second true -> B; 75 -> B; 74 -> C. The ELSE branch already implies Score < 90, so the B test needs no repeated upper bound.
Common mistake: Checking >=75 first would incorrectly classify 95 as B.
Marking points
- Tests the highest condition first: IF Score >= 90 THEN output 'A'.
- Nests an ELSE IF (or ELSE containing IF) testing Score >= 75 to output 'B'.
- Provides a final ELSE branch that outputs 'C' for any remaining score.
Examiner tip: Testing from the highest boundary downward avoids a lower condition like Score >= 75 wrongly catching a 95 before it reaches the 'A' check.
- 7.
Explain one advantage of using a function (subroutine) rather than repeating the same code several times in a program.
[2 marks] · no calculatorWorked explanation
- Put repeated logic into a single reusable function: for example, `def area(w,h): return w*h` can serve calls `area(3,4)` and `area(5,2)`.
- If that calculation must change, update and test one implementation instead of editing multiple copied blocks. The calls still pass their own values; reuse does not require every caller to have the same result.
Common mistake: Functions do not automatically make code faster; the stated advantage is consistent reuse and maintenance.
Marking points
- States a valid benefit of one reusable subroutine, such as avoiding duplicated code, making maintenance easier or testing the logic independently.
- Explains the chosen benefit, such as correcting the logic once rather than maintaining several copies; accept other valid linked explanations.
Examiner tip: Repeated code must be found and changed everywhere it appears; a function only needs to be changed once.
- 8.
A form accepts an age as a whole number from 1 to 120 inclusive. Explain how a range check and a type check can each validate this input.
[4 marks] · no calculatorWorked explanation
- A type check rejects non-integer input such as 'ten' or 12.5; converting 12.5 by truncation would not validate the original entry as a whole number.
- After successful integer parsing, require 1 <= Age <= 120. Trace 0 -> reject range, 1 -> accept, 120 -> accept, 121 -> reject. Integer 200 passes type but fails range, so both checks are needed.
Common mistake: A range check alone accepts some decimals numerically between the limits.
Marking points
- Identifies a range check.
- Explains that a range check confirms the value falls between 1 and 120 inclusive.
- Identifies a type check.
- Explains that a type check confirms the value entered is a whole number (integer), not text or a decimal.
Examiner tip: A range check and a type check examine different properties of the same input and are often both needed together.
- 9.
A loop runs the pseudocode 'Count ← Count + 1' three times, starting with Count = 0. Complete a trace table showing the value of Count after each of the three iterations.
[3 marks] · no calculatorWorked explanation
- Trace table: before loop Count=0; after iteration 1 Count=1; after 2 Count=2; after 3 Count=3.
- Each assignment reads the old Count then adds one. Executable Python: Count = 0 for iteration in range(1,4): Count = Count + 1 print(iteration, Count)
Common mistake: Recording 0 as the value after iteration one confuses the initial state with the first updated state.
Marking points
- States that Count = 1 after the first iteration.
- States that Count = 2 after the second iteration.
- States that Count = 3 after the third iteration.
Examiner tip: A trace table tracks how a variable's value changes step by step as a program or loop executes.
- 10.
Write pseudocode to calculate and output the average of 5 numbers stored in an array called Marks.
[4 marks] · no calculatorWorked explanation
- For a 1-based five-element array: Total <- 0 FOR i <- 1 TO 5 Total <- Total + Marks[i] NEXT i Average <- Total / 5 OUTPUT Average
- For illustrative Marks [10,20,30,40,50], cumulative totals are 10,30,60,100,150 and the average is 30. Python companion `sum([10,20,30,40,50])/5` checks this, but the pseudocode shows the requested traversal.
Common mistake: Resetting Total inside the loop leaves only the last mark rather than the sum.
Marking points
- Declares a total variable initialised to zero before the loop.
- Uses a loop to add each of the 5 array elements to the total.
- Divides the final total by 5 after the loop ends to calculate the average.
- Outputs the calculated average.
Examiner tip: Always initialise a running total to zero before a loop begins adding to it; forgetting this gives an incorrect result.
- 11.
Explain the difference between a variable and a constant in a program.
[2 marks] · no calculatorWorked explanation
- A variable names stored data that may change during execution, for example Count moving from 0 to 1 after an item is processed.
- A declared constant fixes an intended value such as DAYS_PER_WEEK = 7 and cannot be reassigned in the language's constant mechanism. Python uppercase names are only a convention, so they do not by themselves enforce immutability.
Common mistake: Calling a value constant just because this run did not change it is not the same as declaring an enforced constant.
Marking points
- Explains that a variable's value can be changed while the program is running.
- Explains that a constant's value is fixed and set once, and cannot be changed while the program runs.
Examiner tip: Use a constant for a value that should never change during execution, such as the number of days in a week, to prevent it being accidentally altered.
- 12.
Explain why a 2D array would be a suitable data structure to store the seating plan of a cinema with rows and columns of seats.
[2 marks] · no calculatorWorked explanation
- Use a row index and a column index to identify each seat, storing availability at Seats[row,column] so the representation mirrors the physical layout.
- Python zero-based example: `seats=[[False for c in range(5)] for r in range(3)]; seats[1][2]=True` reserves the third seat of the second row. Independent row creation prevents a change from appearing in every row.
Common mistake: One index cannot directly identify both a row and a column without an extra mapping rule.
Marking points
- Explains that a 2D array organises data using two indices, which can directly represent a row number and a column number.
- Explains that this makes it easy to store and access the status of a seat at any specific row and column position, matching the real layout.
Examiner tip: A 2D array is a natural fit whenever real-world data is already organised in a grid, such as rows and columns of seats.
- 13.
Explain what the string length function would return when applied to the text 'Cambridge', and give one reason a programmer might need this value.
[2 marks] · no calculatorWorked explanation
- Count the characters C,a,m,b,r,i,d,g,e: length is 9. Python `len('Cambridge')` returns 9, not the last zero-based index 8.
- A validation check can reject a username longer than eight characters; this particular text would fail that illustrative maximum. Length checks do not verify that a name is genuine.
Common mistake: Subtracting one because indexing starts at zero confuses an index with a count.
Marking points
- States that the length function would return 9, since 'Cambridge' has 9 characters.
- States a valid reason, such as validating that a username or password meets a minimum or maximum length requirement.
Examiner tip: String length functions are commonly used in validation, to check an input is neither too short nor too long before accepting it.
- 14.
Distinguish between a count-controlled loop and a condition-controlled loop, using an example of when each would be appropriate.
[2 marks] · no calculatorWorked explanation
- A count-controlled loop suits five stored marks: `for i in range(5): print(i)` executes five times with indices 0-4.
- A condition-controlled loop suits repeated input until 0<=score<=100, because invalid attempts are not known in advance. A pre-test loop may execute zero times; a post-test loop executes at least once.
Common mistake: A condition loop still needs an update or new input capable of making its continuation condition false.
Marking points
- Explains that a count-controlled loop (such as a FOR loop) repeats a fixed, known number of times, suitable for processing every element of an array of known size.
- Explains that a condition-controlled loop (such as a WHILE loop) repeats until a condition becomes true or false, suitable when the number of repetitions is not known in advance, such as repeating until valid input is entered.
Examiner tip: Choose a count-controlled loop when you know exactly how many repetitions you need in advance; choose a condition-controlled loop when you do not.
- 15.
The list [8, 3, 6, 1] is sorted into ascending order using an insertion sort. State the list after the algorithm has correctly inserted the second element (3) into its sorted position among the first two elements.
[2 marks] · no calculatorCourse scope: Optional enrichment
Worked explanation
- The sorted prefix initially contains [8]. Save the second element 3, compare with 8 and shift 8 one place right.
- Insert saved 3 into the vacated position, giving [3,8,6,1]. The untouched suffix [6,1] remains unsorted; Python `a=[8,3,6,1]; key=a[1]; a[1]=a[0]; a[0]=key` reproduces this first insertion.
Common mistake: Sorting the whole list goes beyond the requested insertion of just the second element.
Marking points
- Compares 3 with 8 and finds 3 is smaller.
- Shifts 8 to the right and inserts 3 before it, giving [3, 8, 6, 1].
Examiner tip: Insertion sort builds a sorted section at the start of the list one element at a time, shifting larger elements right to make room.
- 16.
Write pseudocode for a linear search that looks for a Target value in an array called Items, and outputs whether the value was found.
[4 marks] · no calculatorWorked explanation
- For N items indexed 1-N: Found <- FALSE FOR i <- 1 TO N IF Items[i] = Target THEN Found <- TRUE ENDIF NEXT i IF Found THEN OUTPUT "found" ELSE OUTPUT "not found" ENDIF
- With Items [4,9,2] and Target 9, Found traces false,true,true; with Target 7 it stays false. A match must not be erased by later nonmatches, and an empty array should report not found.
Common mistake: Outputting 'not found' on the first nonmatch skips later elements that might match.
Marking points
- Traverses Items in order, using suitable bounds; accepts an early exit after a match or a full traversal.
- Compares the current element with Target.
- Records a match without overwriting it after later nonmatches, or reports found and exits; accepts a Found flag initialised FALSE and set TRUE on a match.
- Outputs a correct found/not-found outcome, either after traversal using the flag or through equivalent early-exit logic; does not report not found merely because one item differs.
Examiner tip: A linear search checks every element one at a time until a match is found or the list ends — simple, but slower than binary search on large sorted lists.
- 17.
Explain what a decision (diamond-shaped) symbol represents in a flowchart.
[2 marks] · no calculatorWorked explanation
- A decision diamond evaluates a Boolean condition such as Score >= 50 rather than performing an unconditional assignment.
- The true-labelled arrow might lead to 'pass' and the false-labelled arrow to 'retry'. Label both paths so control flow for a value such as Score=49 is unambiguous.
Common mistake: Drawing two unlabeled exits leaves the condition's outcome-to-path mapping undefined.
Marking points
- Explains that a decision symbol represents a point where the program checks a condition, which is either true or false.
- Explains that the flowchart branches into different paths depending on the result of this check.
Examiner tip: Every path leaving a decision symbol should be clearly labelled, usually 'Yes'/'No' or 'True'/'False'.
- 18.
Write pseudocode to count how many values in an array called Scores are greater than 50.
[4 marks] · no calculatorWorked explanation
- For N scores: Count <- 0 FOR i <- 1 TO N IF Scores[i] > 50 THEN Count <- Count + 1 ENDIF NEXT i OUTPUT Count
- For [50,51,20,80], counter values are 0,1,1,2. Python `sum(1 for x in [50,51,20,80] if x>50)` confirms 2; equality at 50 must not count.
Common mistake: Adding Scores[i] totals values rather than counting qualifying entries.
Marking points
- Declares a counter variable initialised to zero before the loop.
- Uses a loop to check every element of the array in turn.
- Increases the counter by 1 only when an element is greater than 50.
- Outputs the final counter value after the loop ends.
Examiner tip: A counting algorithm only increases its counter when the condition is met, unlike a totaling algorithm, which adds the actual value every time.
- 19.
Explain one advantage of writing a procedure that accepts parameters, rather than one that always works on fixed, built-in values.
[2 marks] · no calculatorWorked explanation
- A parameter makes the same procedure operate on caller-supplied data. Python `def greet(name): print('Hello',name)` can be called with `greet('Amira')` and `greet('Ben')`.
- Both calls share one implementation but produce the appropriate name. Changing the greeting once changes every caller's behaviour, avoiding almost-identical hard-coded procedures.
Common mistake: A parameter is not limited to the first value ever passed; each call can supply a new argument.
Marking points
- Explains that a procedure with parameters can be reused with different input values each time it is called, instead of only ever working on one fixed value.
- Explains that this makes the code more flexible and avoids having to write a near-identical procedure for every different input value needed.
Examiner tip: Parameters let one procedure handle many different cases, rather than needing a separate, duplicated procedure for each specific value.
- 20.
A form requires a user to enter their name. Explain what a presence check would do, and why it is needed for this field.
[2 marks] · no calculatorWorked explanation
- A presence check rejects a missing name, at minimum an empty string, because the field is required for a usable form submission.
- A practical Python check `bool(name.strip())` also rejects whitespace-only entries: '' and ' ' fail, 'Amira' passes. It still does not establish that the entered name is real or correctly spelt.
Common mistake: Presence is not correctness; 'xyz' can be present without being the intended name.
Marking points
- Explains that a presence check confirms that the user has not left the field completely empty.
- Explains that this is needed because a name field is a required piece of data, and the program should not accept a submission that is missing it.
Examiner tip: A presence check is the simplest form of validation: it only confirms that something was entered, not that it is the right kind of data.
- 21.
A system requires a new password to be at least 8 characters long. Explain what a length check would do when this password is entered.
[2 marks] · no calculatorWorked explanation
- Count the entered characters and accept the length rule only if count >= 8. Pseudocode: IF LENGTH(Password) < 8 THEN OUTPUT "too short" ELSE OUTPUT "length accepted" ENDIF.
- Boundary trace: 'abcdefg' has 7 characters and fails; 'abcdefgh' has 8 and passes. This check alone says nothing about guessing resistance or whether the password is already compromised.
Common mistake: Using >8 as the acceptance condition rejects the allowed eight-character boundary.
Marking points
- Explains that a length check counts the number of characters entered.
- Explains that it rejects the input if this count is below the minimum (or above a maximum, if one is set) allowed length.
Examiner tip: A length check specifically counts characters; it does not check whether those characters are of the correct type.
- 22.
Explain, in simple terms, what it means for a function to be recursive, using a function that calculates factorials as an example.
[2 marks] · no calculatorCourse scope: Optional enrichment
Worked explanation
- A recursive function calls itself on a smaller subproblem. For nonnegative integer n, factorial uses n! = n*(n-1)! with base case 0! = 1.
- Python teaching example: def factorial(n): if n < 0: raise ValueError('nonnegative required') if n == 0: return 1 return n * factorial(n-1) print(factorial(4)) The calls descend 4,3,2,1,0, then return 1,1,2,6,24. This example assumes integer input.
Common mistake: Without a reachable base case, recursive calls continue until a runtime limit rather than yielding a factorial.
Marking points
- Explains that a recursive function is a function that calls itself as part of its own execution.
- Applies this to the example: a factorial function can calculate factorial(n) by calling itself to calculate factorial(n-1), and so on, until it reaches a base case.
Examiner tip: Every recursive function needs a base case — a point where it stops calling itself — otherwise it would repeat forever.
- 23.
Explain one feature of an Integrated Development Environment (IDE) that helps a programmer write code with fewer errors.
[2 marks] · no calculatorWorked explanation
- An IDE's syntax-aware editor can flag an unclosed bracket before execution: for example `print('hello'` lacks its closing parenthesis.
- An error marker directs the programmer to add `)`, producing `print('hello')`. This catches syntax problems early, but a syntactically valid wrong calculation still needs tests and debugging.
Common mistake: No red syntax marks does not prove the program's logic satisfies its requirements.
Marking points
- Identifies a valid feature, such as syntax highlighting, auto-complete, or a built-in debugger.
- Explains how this feature helps, such as syntax highlighting making it easier to spot a missing bracket or misspelled keyword.
Examiner tip: IDE tools exist specifically to catch common mistakes early, before the program is even run.
- 24.
Explain the purpose of using meaningful variable names, such as 'studentAge' instead of 'x', when writing a program.
[2 marks] · no calculatorWorked explanation
- `studentAge = 15` makes the stored quantity clear, whereas `x = 15` requires surrounding context to identify its purpose.
- Later code such as `studentAge >= 16` communicates its eligibility test directly, making review and correction easier. Meaningful naming aids human maintenance; it does not make an otherwise wrong threshold logically correct.
Common mistake: A descriptive name is not a substitute for validation or testing the value it holds.
Marking points
- Explains that a meaningful name makes it clear what kind of data the variable stores, without needing to read the surrounding code carefully.
- Explains that this makes the program easier for the original programmer, or someone else, to read, understand and maintain later.
Examiner tip: Meaningful names cost nothing to the computer running the program, but save real time for any human who later reads the code.