Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4.
Read the whole file one line at a time. Keep a moving window of the last three lines: each new line pushes the older ones along.
PROCEDURE LastLines(ThisFile : STRING)
DECLARE ThisLine, LineX, LineY, LineZ : STRING
OPENFILE ThisFile FOR READ
LineY ← ""
LineZ ← ""
WHILE NOT EOF(ThisFile)
READFILE ThisFile, ThisLine
LineX ← LineY
LineY ← LineZ
LineZ ← ThisLine
ENDWHILE
CLOSEFILE ThisFile
OUTPUT LineX
OUTPUT LineY
OUTPUT LineZ
ENDPROCEDUREProcedure heading with the parameter, and ending [1]
Local variables for the three lines declared, and the file opened for READ and closed [1]
Loop until EOF(ThisFile) [1]
A line read from the file inside the loop [1]
LineX, LineY and LineZ shuffled correctly (LineX ← LineY, LineY ← LineZ, LineZ ← ThisLine) in the loop [1]
The three lines output in the correct order after the loop, following a reasonable attempt [1]
Other points that also score: an attempt at shuffling the lines along inside the loop.
An alternative with two loops also scores: count the lines, close and reopen the file, skip (Count - 3) lines, then read and output the last three.
Write any three changes:
Change the procedure heading to add a numeric parameter (the number of lines) as well as the file name [1]
Replace LineX, LineY and LineZ with an array [1]
Change the shuffle so it works for any number of lines [1]
Other points that also score: use the new parameter to decide the first line to output; output the lines in a loop. With the two-loop method, the points are: add the numeric parameter, count the lines in a first loop, use a single variable instead of LineX, LineY and LineZ, close and reopen the file, use the parameter to decide the first line, and output the lines in a loop.
▶ Whole paper
Video solution of the whole paper · by Awab Aqib. Tap the picture to open it on YouTube.
Solutions follow the official Cambridge mark schemes; marks are shown in grey. Videos are from other YouTube channels. Paper codes read component / series / year: M/J = May/June, O/N = October/November. Past-paper questions © UCLES, reproduced for classroom practice.