How to Find Average of All Elements in a List in C++?
Last Updated :
16 Apr, 2024
In C++, the STL provides a list container that is a doubly-linked list that allows storing the data in non-continuous memory locations. In this article, we will learn how to find the average of all elements in a list in C++.
Example:
Input:
myList = {10, 20, 30, 40, 50};
Output:
Average of all elements in the list is : 30
Finding the Average of All Elements in a List in C++
To find the average or mean of all elements in a std::list, we can use the std::accumulate() function to get the sum of all the elements in the list, and then divide the sum by the size of the list that can be found using std::list::size() to get the average of all elements.
Approach
- First, calculate the size of the std::list using the std::list::size() method.
- Check if n is equal to 0 if yes, print the average as 0.
- Now, calculate the sum of all elements in the list using the std::accumulate() function.
- Return the average as sum / n.
C++ Program to Find the Average of All Elements in a List
The following program demonstrates how we can find the average of all elements in a list in C++.
C++
// C++ program to find the average of all elements in a list
#include <iostream>
#include <list>
#include <numeric>
using namespace std;
int main()
{
// Initializing a list of integers
list<int> ls = { 10, 20, 30, 40, 50 };
// size of list
int n = ls.size();
if (n == 0)
cout << "Average of all elements in the list is: "
<< 0 << endl;
else {
// sum of the list elements
double sum = accumulate(ls.begin(), ls.end(), 0.0);
// average of the list elements
double avg = sum / n;
cout << "Average of all elements in the list is: "
<< avg << endl;
}
return 0;
}
OutputAverage of all elements in the list is: 30
Time Complexity: O(N), where N is the number of elements in the list.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...