Demo - Vector
An example C++ program that uses a vector to store a collection of integers, adds new integers to the vector, and calculates the average of the values in the vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector;
// Add some values to the vector
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
// Calculate the average of the values in the vector
int sum = 0;
for (int i = 0; i < myVector.size(); i++) {
sum += myVector[i];
}
double average = (double)sum / myVector.size();
// Print the average to the console
cout << "Average: " << average << endl;
return 0;
}
This C++ program is used to demonstrate how to work with a vector, which is a type of dynamic array, and calculate the average of its values. Here's an explanation of what each part of the code does:
Library Inclusion and Namespace
The program starts by including the
iostream
andvector
libraries.iostream
is used for input/output operations, andvector
is a template class in the Standard Template Library (STL) that is used to represent arrays that can change in size. Theusing namespace std;
line allows the program to use functions from thestd
namespace without having to prefix them withstd::
.Main Function
The
main()
function starts with declaring a vector of integersmyVector
. This is an empty vector that can holdint
values.The program then uses the
push_back()
function to add (or "push") three integers (10, 20, and 30) to the end of the vector.The program then calculates the average of the values in the vector. It first initializes an
int
variablesum
to 0. It then uses afor
loop to iterate through the vector, adding each element tosum
. After the loop, the sum of the vector's elements is calculated.The average is then calculated by dividing the sum (which is cast to
double
to allow for decimal places in the average) by the number of elements in the vector (which is returned bymyVector.size()
). The result is stored in thedouble
variableaverage
.Output
The average is then printed to the console using the
cout
statement.Given the initial values in the vector, the output of this program will be: 20. This is because the sum of 10, 20, and 30 is 60, and there are three elements, so the average is 60 / 3 = 20.
COSC-1336 / ITSE-1302 Computer Science - Author: Dr. Kevin Roark