9618/22/M/J/24 question 8: worked solution (May/June 2024, paper 22)
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. Q59 9618/22/M/J/24 original Q8 Structured · 16 marks Worked solution (a) Give a reason and a benefit: Reason: the program is easier to design, test, debug or modify in separate stages [1] Benefit: it is easier to check that each stage works as expected by looking at its own file [1] (b) Find the position of the first character that is not a space. Then keep the rest of the line from that point. FUNCTION DeleteSpaces(Line : STRING) RETURNS STRING DECLARE NewLine : STRING DECLARE EndOfLeading : BOOLEAN DECLARE Count, NumSpaces : INTEGER DECLARE NextChar : CHAR CONSTANT Space = " " NumSpaces ← 0 EndOfLeading ← FALSE FOR Count ← 1 TO LENGTH(Line) NextChar ← MID(Line, Count, 1) IF NextChar <> Space AND EndOfLeading = FALSE THEN NumSpaces ← Count - 1 EndOfLeading ← TRUE ENDIF NEXT Count NewLine ← RIGHT(Line, LENGTH(Line) - NumSpaces) RETURN NewLine ENDFUNCTION Loop through the length of Line (or until the first non-space) [1] Extracts a character inside the loop [1] Identifies the first non-space character inside the loop [1] Attempts to remove the leading spaces from Line [1] The leading spaces are removed correctly (a new string without them) [1] Returns the string after a reasonable attempt [1] (c) Clean each line with both modules. Write it only if it is not empty. Otherwise count it as a blank line. PROCEDURE Stage_2(F1, F2 : STRING) DECLARE Line : STRING DECLARE Count : INTEGER Count ← 0 OPENFILE F1 FOR READ OPENFILE F2 FOR APPEND WHILE NOT EOF(F1) READFILE F1, Line Line ← DeleteSpaces(Line) Line ← DeleteComment(Line) IF Line <> "" THEN WRITEFILE F2, Line ELSE Count ← Count + 1 ENDIF ENDWHILE CLOSEFILE F1 CLOSEFILE F2 OUTPUT Count, " blank lines were removed" ENDPROCEDURE Procedure heading, parameters and ending [1] Both files opened in the correct modes (F1 for read, F2 for append because it already exists) and closed afterwards [1] Loop that runs until EOF(F1) [1] Reads a line from F1 inside the loop [1] Assigns the values returned by DeleteComment() and DeleteSpaces() inside the loop [1] Checks the result is not empty and, if so, writes it to F2 inside the loop [1] Counts the blank lines inside the loop [1] Outputs the number of blank lines removed after the loop [1] KEY IDEA Small modules can be chained: clean the line twice, then write only what is left and count what is dropped. TOTAL 16 marks Official mark scheme VIDEO ▶ Starts at Q8 (1:12:50) Starts at Q8 (1:12:50) · by Pseudocode Pro. Tap the picture to open it on YouTube.