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:

  1. Library Inclusion and Namespace

    The program starts by including the iostream and vector libraries. iostream is used for input/output operations, and vector is a template class in the Standard Template Library (STL) that is used to represent arrays that can change in size. The using namespace std; line allows the program to use functions from the std namespace without having to prefix them with std::.

  2. Main Function

    The main() function starts with declaring a vector of integers myVector. This is an empty vector that can hold int 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 variable sum to 0. It then uses a for loop to iterate through the vector, adding each element to sum. 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 by myVector.size()). The result is stored in the double variable average.

  3. 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