Using vectors to calculate the average

Using vectors to calculate the average
This C++ example shows you how to store a set of numbers into vectors and loop through the values in order to get the average of those numbers.
1.  #include <cstdlib>
2.  #include <iostream>
3.  #include <vector>
4.   
5.  using namespace std;
6.   
7.  int main()
8.  {
9.      // Vector of size 10
10.     vector<int> SemesterGrades(10);
11.     // Get the values in
12.     for(int i = 0; i < 10; i++)
13.     {
14.             cout << "Enter grade #" << (i + 1) << ": ";
15.             cin >> SemesterGrades[i];
16.     }
17.    
18.     // Calculate the average
19.     int Total = 0;
20.     for(int i = 0; i < 10; i++)
21.     {
22.             // Add to the total
23.             Total += SemesterGrades[i];
24.     }
25.     // Divide to get the average
26.     double Average = (double)Total / 10;
27.     // Display the result
28.     cout << "\r\nThe total is " << Total << ", the average is " << Average << "\r\n";
29.     // Wait for user input before ending the console application
30.     system("PAUSE");
31.     return 0;
32. }
33.  

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top