Worked example 1
A text file, Scores.txt, contains a list of scores, one per line. Write pseudocode to read all the scores from the file, calculate their total, and output the final total.
File Content (Scores.txt):
150
230
95
Show solution outline
// 1. Initialise variables
DECLARE TotalScore : INTEGER
DECLARE CurrentScore : INTEGER
TotalScore <- 0
// 2. Open file for reading
OPENFILE "Scores.txt" FOR READ
// 3. Loop until the end of the file
WHILE NOT EOF("Scores.txt")
// 4. Read a line and add to total
READFILE "Scores.txt", CurrentScore
TotalScore <- TotalScore + CurrentScore
ENDWHILE
// 5. Close the file
CLOSEFILE "Scores.txt"
// 6. Output the result
OUTPUT "Total score is: ", TotalScore
Mark Scheme:
- 1 mark for initialising TotalScore.
- 1 mark for opening the file in READ mode.
- 1 mark for a correct loop condition (WHILE NOT EOF).
- 1 mark for correctly reading from the file inside the loop.
- 1 mark for correctly accumulating the total inside the loop.
- 1 mark for closing the file.
Expected Output: Total score is: 475