File Operations CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
hardA program reads a CSV file where each line has 'name,score' (e.g., 'Alice,85'). Write pseudocode to find the student with the highest score and output their name.
Solution
- 1 Step 1: OPEN 'scores.csv' FOR READING. SET bestName = ''. SET bestScore = -1. WHILE NOT end of file: line = READ line. parts = SPLIT(line, ','). name = parts[0]. score = INT(parts[1]).
- 2 Step 2: IF score > bestScore THEN bestScore = score. bestName = name. CLOSE file. OUTPUT bestName + ' with score ' + STRING(bestScore).
- 3 Step 3: This uses the 'find maximum' pattern combined with CSV parsing (splitting each line by the delimiter).
Answer
Read each line, split by comma, track the highest score. Output the name of the top scorer.
CSV (comma-separated values) is a common file format. Parsing it requires splitting strings by a delimiter, converting types, and applying algorithms like finding the maximum.
About File Operations
The operations of reading data from files and writing data to files on a storage device, allowing programs to persist information beyond a single run. The standard pattern is: open the file, read from or write to it, then close the file to ensure data is saved properly.
Learn more about File Operations โMore File Operations Examples
Example 1 easy
Write pseudocode to write three names to a file called 'names.txt', then read them back and display
Example 2 mediumExplain the difference between opening a file in WRITE mode vs APPEND mode. When would you use each?
Example 3 mediumWrite pseudocode that reads a file of numbers (one per line), calculates their total, and writes the