9618/21/M/J/24 question 8: worked solution (May/June 2024, paper 21)
Show as plain textHide plain text
Cambridge AS Level Computer Science 9618 · 10.3 Files Worked solution from the Data Types and Structures Paper 2 Problem-solving and Programming booklet, Part 3 of 4. Q57 9618/21/M/J/24 original Q8 Structured · 15 marks Worked solution (a) Look for "//" by taking two characters at a time. Stop at the first one, remember where it starts, and keep only the text before it. FUNCTION DeleteComment(Line : STRING) RETURNS STRING DECLARE NewLine, TwoChars : STRING DECLARE Count, TrimTo : INTEGER CONSTANT Comment = "//" NewLine ← Line TrimTo ← 0 Count ← 1 WHILE Count < LENGTH(Line) AND TrimTo = 0 TwoChars ← MID(Line, Count, 2) IF TwoChars = Comment THEN TrimTo ← Count ENDIF Count ← Count + 1 ENDWHILE IF TrimTo <> 0 THEN NewLine ← LEFT(Line, TrimTo - 1) ENDIF RETURN NewLine ENDFUNCTION Loop that goes up to the length of Line [1] Loop stops at the first double slash [1] Extracts one or two characters inside the loop [1] Checks for "//" after extracting, inside the loop [1] Records the start position of the comment (or the amount to trim) [1] Attempts to trim Line from the start of the comment [1] The trimmed line is completely correct (everything before the comment) [1] Returns the line [1] (b) Build the two file names, read each line, remove the comment with DeleteComment(), then write only the lines that are not empty. Count the lines written. FUNCTION Stage_1(StudentName : STRING) RETURNS INTEGER DECLARE OldFile, NewFile, Line : STRING DECLARE Count : INTEGER OldFile ← StudentName & "_src.txt" NewFile ← StudentName & "_S1.txt" OPENFILE OldFile FOR READ OPENFILE NewFile FOR WRITE Count ← 0 WHILE NOT EOF(OldFile) READFILE OldFile, Line Line ← DeleteComment(Line) IF LENGTH(Line) <> 0 THEN WRITEFILE NewFile, Line Count ← Count + 1 ENDIF ENDWHILE CLOSEFILE OldFile CLOSEFILE NewFile RETURN Count ENDFUNCTION Both file names made from StudentName (a missing underscore is forgiven) [1] Both files opened in the correct modes (READ and WRITE) and closed afterwards [1] Loop that runs until EOF of the project file [1] Reads a line and calls DeleteComment() inside the loop [1] Skips blank lines after DeleteComment() inside the loop [1] Writes the line to the stage 1 file and adds 1 to Count inside the loop [1] Returns the number of lines written [1] KEY IDEA Break a file task into small modules: clean each line with a function, skip empty results and count what you write. TOTAL 15 marks Official mark scheme VIDEO ▶ Starts at Q8 (1:19:38) Starts at Q8 (1:19:38) · by Pseudocode Pro. Tap the picture to open it on YouTube.