I l@ve RuBoard |
![]() ![]() |
Exercise 1.6Write a program to read in a sequence of integers from standard input. Place the values, in turn, in a built-in array and a vector. Iterate over the containers to sum the values. Display the sum and average of the entered values to standard output. The built-in array and the vector class differ in primarily the same ways as the C-style character string (which is implemented as an array of char elements) and the string class: (1) The built-in array must be of a fixed size, whereas the vector can grow dynamically as elements are inserted, and (2) the built-in array does not know its size. The fixed-size nature of the built-in array means that we must be concerned with potentially overflowing its boundary. Unlike the C-style string, the built-in array has no sentinel value (the null) to indicate its end. Particularly for beginners, I recommend that the vector class be used in favor of the built-in array. Here is the program using the vector class: #include <iostream> #include <vector> using namespace std; int main() { vector<int> ivec; int ival; while ( cin >> ival ) ivec.push_back( ival ); // we could have calculated the sum as we entered the // values, but the idea is to iterate over the vector ... for ( int sum = 0, ix = 0; ix < ivec.size(); ++ix ) sum += ivec[ ix ]; int average = sum / ivec.size(); cout << "Sum of " << ivec.size() << " elements: " << sum << ". Average: " << average << endl; } The primary difference in the following built-in array implementation is the need to monitor the number of elements being read to ensure that we don't overflow the array boundary: #include <iostream> using namespace std; int main() { const int array_size = 128; int ia[ array_size ]; int ival, icnt = 0; while ( cin >> ival && icnt < array_size ) ia[ icnt++ ] = ival; for ( int sum = 0, ix = 0; ix < icnt; ++ix ) sum += ia[ ix ]; int average = sum / icnt; cout << "Sum of " << icnt << " elements: " << sum << ". Average: " << average << endl; } ![]() |
I l@ve RuBoard |
![]() ![]() |