home *** CD-ROM | disk | FTP | other *** search
- /*
- C++ program that demonstrates the use of pointers with
- one-dimension arrays. The average value of the array
- is calculated. This program modifies the previous version
- in the following way: the realPtr is used to access the
- array without any help from any loop control variable.
- This is accomplished by 'incrementing' the pointer, and
- consequently incrementing its address. This program
- illustrates pointer arithmetic that alters the pointer's
- address.
-
- */
-
- #include <iostream.h>
-
- const int MAX = 30;
-
- main()
- {
-
- double x[MAX];
- double *realPtr = x;
- double sum, sumx = 0.0, mean;
- int i, n;
-
- do {
- cout << "Enter number of data points [2 to "
- << MAX << "] : ";
- cin >> n;
- cout << "\n";
- } while (n < 2 || n > MAX);
-
- // loop variable i is not directly involved in accessing
- // the elements of array x
- for (i = 0; i < n; i++) {
- cout << "X[" << i << "] : ";
- // increment pointer realPtr after taking its reference
- cin >> *realPtr++;
- }
-
- // restore original address by using pointer arithmetic
- realPtr -= n;
- sum = n;
- // loop variable i serves as a simple counter
- for (i = 0; i < n; i++)
- // increment pointer realPtr after taking a reference
- sumx += *(realPtr++);
- mean = sumx / sum;
- cout << "\nMean = " << mean << "\n\n";
- return 0;
-
- }