Lesson goal: Total all numbers in a data file

Previous: Testing for the end of file (EOF) | Home | Next: Find the average of some numbers

With the looping and file reading all under control, let's finally start doing some DATA SCIENCE! What we mean by 'data science,' is to see if we can write some code to extract some meaning from the data.

To start, suppose that sample.dat contains a list of amounts spent by patrons during lunch at a retaurant. Let's see if we can tell the owner what his total earnings were. In other words, let's find the sum of all numbers in the file sample.dat.

As is typical in such work, we'll need to set up a loop to be able to examine each number in the file. But we won't just print them to the screen. We'll apply some coding logic to try and figure what the sum total of all numbers in the file.

In other words, let's add up all of the numbers in sample.dat.

Since we'll be treating the reads from our file as numbers now, we'll use a new function called file_read_number, which is just like file_read, but formats all data coming in from a file as a real number. It works like this:
num=file_read_number(handle)
Move the mouse over a dotted box for more information.

Now you try. Try to complete the code and find the minimum number in the file sample.dat.

Type your code here:


See your results here: