Open In App

How to Find the Average of All Elements in a Vector in C++?

In C++, a vector is a dynamic array that can grow and shrink in size as needed. It is part of the Standard Template Library (STL). In this article, we will learn how to find the average (or mean) of all elements in a vector in C++.

Example:

Input:
 myVector = {1, 2, 3, 4, 5}

Output:
mean = 3

Find the Average of Vector Elements in C++

To find the average or mean of all elements in a vector in C++, we can use the std::accumulate() function to calculate the sum and then divide it by the number of elements that can be found using std::vector::size().



Syntax of std::accumulate

accumulate(first_index, last_index, initial value of sum);

Approach

  1. Calculate the size of the vector using the size() function.
  2. If n is equal to 0 return 0.
  3. Calculate the sum of all elements in the vector in ‘sum’ using the accumulate() function.
  4. Return the average as sum / n.

C++ Program to Find the Average of All Elements in a Vector




// C++ Program to find the Average of all elements
// in a Vector
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> v = { 1, 2, 3, 4, 5 };
  
    // size of vector
    int n = v.size();
    if (n == 0)
        cout << "Average: " << 0 << endl;
  
    else {
        // sum of the vector elements
        double sum = accumulate(v.begin(), v.end(), 0.0);
  
        // average of the vector elements
        double avg = sum / n;
        cout << "Average: " << avg << endl;
    }
  
    return 0;
}

Output
Average: 3

Time Complexity: O(n), where n is the number of elements in the vector.
Auxiliary Space: O(1)



Article Tags :