Adding elements to one sum

CanĀ“t figure out how to add values from a vector in a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 #include <iostream>
#include <vector>
#include <numeric>

using namespace 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;
Last edited on
Fixed it!!!


1
2
3
4
5
6
7
	

for (int i = 0; i < sizeOfVector; ++i)
	{
		sum = sum + vectorValues[i];
	}
	cout << sum;
Topic archived. No new replies allowed.