File Operations CS Thinking Example 4

Follow the full solution, then compare it with the other examples linked below.

Example 4

hard
A 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. 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. 2
    Step 2: IF score > bestScore THEN bestScore = score. bestName = name. CLOSE file. OUTPUT bestName + ' with score ' + STRING(bestScore).
  3. 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