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:

In the code, note the placement of file_read(h), which reads a number from a file.

BUT...the code won't run as is. What should sum be set to? And, complete the line sum = sum + ???. Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.