#include <iostream>
#include <vector>
#include <numeric>
usingnamespace std;
// Function Declarations
float average(vector<int>&);
// average - calculates average value in vector
void print(float);
// print - prints averageValue
// @param float - averageValue to print
// Initiate values
int sum = 0;
int i=0;
double averageValue;
int main()
{
// Initiating vector
cout << "Type in how many measurements you have done: ";
int sizeOfVector;
std::cin >> sizeOfVector;
vector <int> vectorValues(sizeOfVector);
// Initiating loop, vector size is zero
// if i less than ten count up
for (vector<int>::size_type i=0; i < sizeOfVector; i++)
{
// Flush makes sure that the buffer is cleared and the characters are written to their destination
cout << "Enter value to vector #" << i+1 << ": " << flush;
// Enter values into vector
cin >> vectorValues[i];
}
average(vectorValues);
print(averageValue);
return 0;
}
float average(vector<int>& vectorValues)
{
// Adding values from vector into variable sum
sum = vectorValues[0] + vectorValues[1] + vectorValues[2] + vectorValues[3] + vectorValues[4] + vectorValues[5] + vectorValues[6] + vectorValues[7] + vectorValues[8] + vectorValues[9];
// Calculating average value
averageValue = (float) sum / 10;
return averageValue;
}
void print(float averageValue)
{
// Print average value
cout << endl;
cout << "Average value " << averageValue << endl;
}
I want the inserted valus to add eachother from the cin >> sizeOfVector; which are number of elements, from inside the vector. I can add a number of elements like below but my mission is to add them like looping them and everytime the loop goes around and sum is added from the vector in to the variable sum.
1 2 3 4 5 6 7
// Adding values from vector into variable sum
sum = vectorValues[0] + vectorValues[1] + vectorValues[2] + vectorValues[3] + vectorValues[4] + vectorValues[5] + vectorValues[6] + vectorValues[7] + vectorValues[8] + vectorValues[9];
// Calculating average value
averageValue = (float) sum / 10;
return averageValue;