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.  
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top