Home Segments Index Top Previous Next

334: Mainline

The for reading pattern is particularly useful when you want to count the data items as you read them, as in the following amended version of the program in Segment 331:

#include  
double box_volume (double h, double w, double l) {return h * w * l;} 
main ( ) { 
  double height, width, depth; 
  int count; 
  for (count = 0; cin >> height >> width >> depth; ++count) 
    cout << "The volume of a " 
         << height << " by " << width << " by " << depth 
         << " box car is " 
         << box_volume (height, width, depth) << endl; 
  cout << "You have computed the volumes of " 
       << count << " box cars." << endl; 
} 
--- Data ---
10.5 9.5 40.0 
10.5 9.5 50.0 
--- Result --- 
The volume of a 10.5 by 9.5 by 40 box car is 3990 
The volume of a 10.5 by 9.5 by 50 box car is 4987.5 
You have computed the volumes of 2 box cars.