-4

I can't figure out how to use for loop to access the vector's elements to find the average. I tried to look for a solution, but I couldn't find anything. The little piece of code that I wrote doesn't seem like the solution.

#include <iostream>
#include <vector>
using namespace std;

int main() {
   const int VALS_SIZE = 6;
   vector<int> valsVctr(VALS_SIZE);
   unsigned int i;
   int sumVal;
   int avgVal;

   valsVctr.at(0) = 30;
   valsVctr.at(1) = 20;
   valsVctr.at(2) = 20;
   valsVctr.at(3) = 15;
   valsVctr.at(4) = 5;
   valsVctr.at(5) = 10;

   sumVal = 0;
   avgVal = 0;
   /* FIXME: Write for loop to iterate through vector */

   for(int i = 0; i < 7;i++)
   valsVctr[i] = i+1;

   avgVal = sumVal / VALS_SIZE;

   cout << "Avg: " << avgVal << endl;

   return 0;
}
  • 6
    Unrelated, but you're better served not trying to learn C++ from YouTube. It's a complicated language, and you'll want a good book. – Stephen Newell Sep 16 '20 at 01:07
  • 1
    [Here's a list of books generally accepted as good.](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – user4581301 Sep 16 '20 at 01:10

3 Answers3

1

You should not use explicit for loop

for(int i = 0; i < 7;i++)  // 

You got an out of bound access error with i = 6.

Instead use for-range loop instead:

for(const auto& x: valsVctr)
{
    sumVal += x;
}
avgVal = sumVal / VALS_SIZE;

Also, sumVal and avgVal would be better of type float or double instead of int.

artm
  • 17,291
  • 6
  • 38
  • 54
  • 1
    Note: The `const auto &` is for future-proofing. Now you can toss in just about any container of anything and not have to change as much code. – user4581301 Sep 16 '20 at 01:11
  • 1
    You can eliminate the manual loop altogether by using the standard `std::accumulate()` algorithm instead: `sumVal = std::accumulate(valsVctr.begin(), valsVctr.end(), 0);` – Remy Lebeau Sep 16 '20 at 02:33
  • @RemyLebeau yes that would eliminate the loop altogether (the loop is what OP asked for). – artm Sep 16 '20 at 03:09
0

You could use a for loop with iterators:

std::vector<int>::const_iterator iter;
std::vector<int>::const_iterator end_iter(valsVctr.end());
for (iter = valsVctr.begin(); iter != end_iter; ++iter)
{
    std::cout << *iter << endl;
}

This would be more safe than an indexed based for loop.

If you want to use an indexed for loop, use the size method for the limit:

const unsigned int limit = valsVctr.size();
for (unsigned i = 0; i < limit; ++i)
{
      valsVctr[i] = i + 1;
}

Note: the size of the vector was assigned to a temporary variable to prevent the size() method from being called in each iteration (although compilers may perform this optimization at higher optimization levels).

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

each way below works

  1. for(int i = 0; i < 6;i++) sumVal += valsVctr[i];

  2. for(int k : valsVctr) sumVal += k; // c++ 11