File Operations CS Thinking Example 3

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

Example 3

medium
Write pseudocode that reads a file of numbers (one per line), calculates their total, and writes the result to a new file 'total.txt'.

Solution

  1. 1
    Step 1: OPEN 'numbers.txt' FOR READING. SET total = 0. WHILE NOT end of file: num = INT(READ line). total = total + num. CLOSE file.
  2. 2
    Step 2: OPEN 'total.txt' FOR WRITING. WRITE STRING(total). CLOSE file.

Answer

Read numbers in a loop, accumulate total, write result to new file. Remember to convert string to integer when reading.
Combining file reading with data processing is a common pattern. The data read from a file is typically a string and must be converted to the appropriate type for calculations.

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