home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / ptr2.cpp < prev    next >
C/C++ Source or Header  |  1993-03-27  |  1KB  |  42 lines

  1. /*
  2.    C++ program that demonstrates the use of pointer with
  3.    one-dimension arrays.  Program calculates the average
  4.    value of the data found in the array.
  5. */
  6.  
  7. #include <iostream.h>
  8.  
  9. const int MAX = 30;
  10.  
  11. main()
  12. {
  13.  
  14.     double x[MAX];
  15.     // declare pointer and initialize with base
  16.     // address of array x
  17.     double *realPtr = x; // same as = &x[0]
  18.     double sum, sumx = 0.0, mean;
  19.     int n;
  20.     // obtain the number of data points
  21.     do {
  22.         cout << "Enter number of data points [2 to "
  23.              << MAX << "] : ";
  24.         cin >> n;
  25.         cout << "\n";
  26.     } while (n < 2 || n > MAX);
  27.     
  28.     // prompt for the data
  29.     for (int i = 0; i < n; i++) {
  30.         cout << "X[" << i << "] : ";
  31.         // use the form *(x+i) to store data in x[i]
  32.         cin >> *(x + i);
  33.     }
  34.  
  35.     sum = n;
  36.     for (i = 0; i < n; i++)
  37.     // use the form *(realPtr + i) to access x[i]
  38.         sumx += *(realPtr + i);
  39.     mean = sumx / sum;
  40.     cout << "\nMean = " << mean << "\n\n";
  41.     return 0;
  42. }