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

  1. /*
  2.   C++ program that demonstrates the pointers to manage
  3.   dynamic data
  4. */
  5.  
  6. #include <iostream.h>
  7.  
  8. const int MAX = 30;
  9.  
  10. main()
  11. {
  12.  
  13.     double* x;
  14.     double sum, sumx = 0, mean;
  15.     int *n;
  16.          
  17.     n = new int;
  18.     if (n == NULL)
  19.       return 1;
  20.       
  21.     do { // obtain number of data points
  22.         cout << "Enter number of data points [2 to "
  23.              << MAX << "] : ";
  24.         cin >> *n;
  25.         cout << "\n";
  26.     } while (*n < 2 || *n > MAX);
  27.     // create tailor-fit dynamic array
  28.     x = new double[*n];
  29.     if (!x) {
  30.       delete n;
  31.       return 1;
  32.     }
  33.     // prompt user for data
  34.     for (int i = 0; i < *n; i++) {
  35.         cout << "X[" << i << "] : ";
  36.         cin >> x[i];
  37.     }
  38.  
  39.     // initialize summations
  40.     sum = *n;
  41.     // calculate sum of observations
  42.     for (i = 0; i < *n; i++)
  43.         sumx += *(x + i);
  44.  
  45.     mean = sumx / sum; // calculate the mean value
  46.     cout << "\nMean = " << mean << "\n\n";
  47.     // deallocate dynamic memory
  48.     delete n;
  49.     delete [] x;
  50.     return 0;
  51. }
  52.