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