Home Segments Index Top Previous Next

379: Mainline

Now suppose that you want to fill an array using data in a file. You probably do not know exactly how many objects you need to store. Accordingly, you need an approach to dealing with uncertainty.

The simplest approach, albeit one not as elegant as the list-oriented approach you learn about in the hardcopy version of this book, is to define an array that is sure to be large enough to hold all the objects you can possibly encounter. Then, you can proceed to fill that array using a while reading pattern or a for reading pattern.

In the following program, for example, you create an array that can hold up to 100 integers representing distances. Then, you fill part or all of that array with integer distances using a for reading pattern. Then, you use another for loop to add up the integer distances, producing the total length of a trip.

Of course, the program could be written with just one for loop, and no array, but introducing the array makes it easy to perform other computations without rereading the file.

#include   
// Define global integer array: 
int distances[100]; 
main ( ) { 
  // Declare various integer variables: 
  int limit, counter, sum = 0; 
  // Read numbers and write them into array: 
  for (limit = 0; cin >> distances[limit]; ++limit) 
    ; 
  // Display the sum of all integers in the array: 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + distances[counter]; 
  cout << "The sum of the " 
       << limit << " distances traveled is " 
       << sum << endl; 
} 
--- Data ---
57      72      94      22      35 
--- Result --- 
The sum of the 5 distances traveled is 280