Table Of Contents
Previous Section Next Section

Program 37: This Program Has a Point

The following program is designed to zero the array data, but sometimes it does something else.

  1 /************************************************
  2  * Pointer demonstration.                       *
  3  ************************************************/
  4 #include <iostream>
  5
  6 static int data[16];    // Data to be stored
  7 static int n_data = 0;  // Number of items stored
  8
  9 int main()
 10 {
 11     int *data_ptr;      // Pointer to current item
 12
 13     // Zero the data array
 14     for (data_ptr = data+16-1;
 15          data_ptr >= data;
 16          --data_ptr)
 17     {
 18         *data_ptr = 0;
 19     }
 20
 21     // Enter data into the array
 22     for (n_data = 0; n_data < 16; ++n_data) {
 23         std::cout <<
 24             "Enter an item or 0 to end: ";
 25         std::cin >> data[n_data];
 26
 27         if (data[n_data] == 0)
 28             break;
 29     }
 30
 31     // Index for summing
 32     int index;
 33
 34     // Total of the items in the array
 35     int total = 0;
 36
 37     // Add up the items in the array
 38     for (index = 0; index < n_data; ++index)
 39         total += data[index];
 40
 41     // Print the total
 42     std::cout << "The total is: " <<
 43         total << std::endl;
 44
 45     return (0);
 46 }

(Next Hint 87. Answer 21.)

Table Of Contents
Previous Section Next Section