Listing 8, Program Array01.cpp
/*File: Array01.cpp
This C++ program illustrates the use of a simple
one-dimensional array in C++.
The program asks the user to enter five integer
values in succession. It stores the values in
reverse order in an array. Then it displays the
contents of the array in forward order.
Then it computes and displays the average of the
values stored in the array, the minimum value
stored in the array, and the maximum value
stored in the array.
The program displays the following output on the
screen for a typical set of input data:
Enter an integer value: -100
Enter an integer value: -50
Enter an integer value: 0
Enter an integer value: 49
Enter an integer value: 99
Array contents:
99 49 0 -50 -100
Average: -0.4
Minimum: -100
Maximum: 99
************************************************/
#include <iostream>
using namespace std;
class Array01{
public:
static void classMain(){
Array01* ptrToObject = new Array01();
ptrToObject -> doSomething();
}//End classMain function
//-------------------------------------------//
//An instance function of the Array01 class
void doSomething(){
const int size = 5;
long values[size];
//Populate the array in reverse order.
getData(values,size);
//Display contents of the array in forward
// order.
cout << "Array contents:" << endl;
displayData(values,size);
//Compute and display average, minimum, and
// maximum values.
cout << "Average: " << getAvg(values,size)
<< endl;
cout << "Minimum: " << getMin(values,size)
<< endl;
cout << "Maximum: " << getMax(values,size)
<< endl;
}//end doSomething function
//-------------------------------------------//
void getData(long array[],int size){
int count = size - 1;
while(count >= 0){
cout << "Enter an integer value: ";
cin >> array[count];
count = count - 1;
}//end while loop
}//end getData
//-------------------------------------------//
void displayData(long array[],int size){
int count = 0;
while(count < size){
cout << array[count] << " ";
count = count + 1;
}//end while loop
cout << endl;
}//end displayData
//-------------------------------------------//
double getAvg(long array[],int size){
int count = 0;
double sum = 0;
while(count < size){
sum = sum + array[count];
count = count + 1;
}//end while loop
return sum/size;
}//end getAvg
//-------------------------------------------//
long getMin(long array[],int size){
long min = 2147483647;
int count = 0;
while(count < size){
if(array[count] < min){
min = array[count];
}//end if
count = count + 1;
}//end while loop
return min;
}//end getMin
//-------------------------------------------//
long getMax(long array[],int size){
long max = -2147483648;
int count = 0;
while(count < size){
if(array[count] > max){
max = array[count];
}//end if
count = count + 1;
}//end while loop
return max;
}//end getMax
//-------------------------------------------//
};//End Array01 class
//---------------------------------------------//
int main(){
Array01::classMain();
return 0;
}//end main
Listing 8
|