Finding the Mean
The mean (or average) of a non-empty list of n numbers is the sum of the numbers divided by n. For example, the mean of 2, 7, 3, 9, and 13 is (2+7+3+9+13)/5, or 6.8. Write a function mean that takes as input a non-empty list of numbers (of any length > 0) and returns the mean.
Function in C++:-
double mean(list<int> &l1,int n)
//the required function which return double value because mean
can be in decimal also
{
int sum=0; //sum variable is taken to store the sum of all the
elements in list
list <int>:: iterator q=l1.begin(); //we can use
list like array and vector like arr[0],we can only use or access
list either from begin() or from end() so we need to use iterartor
operator for that which act same as the pointer
for(int i=0;i<n;i++) //for loop will run
till "n" i.e. the number of elements in list
{
sum+=*q; //it take the element present at current
location i.e at beginning of the list
q++; //each time it increment the location of
the list and each time it goes to the nest element in the
list
}
return (double)(sum/n); //return (sum/n) i.e the
mean
}
Get Answers For Free
Most questions answered within 1 hours.