Compute the average of the values in vector using array subscripting operator. - C++ STL

C++ examples for STL:vector

Description

Compute the average of the values in vector using array subscripting operator.

Demo Code

#include <iostream>
#include <vector>
using namespace std;
void show(const char *msg, vector<int> vect);
int main() {/*from  w  w  w  .  j a v  a 2 s  .co m*/
   vector<int> v(10);
   for(unsigned i=0; i < v.size(); ++i)
      v[i] = i*i;
   show("Contents of v: ", v);
   int sum = 0;
   for(unsigned i=0; i < v.size(); ++i)
      sum += v[i];
   double avg = sum / v.size();
   cout << "The average of the elements is " << avg << "\n\n";
   return 0;
}
void show(const char *msg, vector<int> vect) {
   cout << msg;
   for(unsigned i=0; i < vect.size(); ++i)
      cout << vect[i] << " ";
   cout << "\n";
}

Result


Related Tutorials