How to calculate the average of an array in C++
The average is the sum of a group of numbers divided by the total number. It is a very important statistical function that provides insights into the data and is used to determine its central tendency. In this Answer, we will learn how to compute an array's average in C++.
Mathematical representation
Mathematically the average function is represented as:
Where,
is the total number of elements in an array. represents the element at the index. represents the average of an array. represents the sum of all the elements present in the array.
Calculating average
Look at the array and the computations below, where we calculate the average of the elements in an array.
Code
The code to compute the average of an array is given below.
#include<iostream>using namespace std;float SumOfArray(float arr[],int TotalNumberofElements){int sum=0;for(int ri=0;ri<TotalNumberofElements;ri++){sum+=arr[ri];}return sum;}float AverageOfArray(float sum,int TotalNumberofElements){return sum/TotalNumberofElements;}int main(){int TotalNumberofElements=5;float arr[TotalNumberofElements]={21,45,23,8,6};float sum=SumOfArray(arr,TotalNumberofElements);float Average=AverageOfArray(sum,TotalNumberofElements);cout<<"The average of an array : "<<Average;}
Line 3–11: The
SumOfArray()function takes the parameter of the array and size and returns the sum of all the elements in an array.Line 12–15:
AverageOfArray()takes thesumof the array andTotalNumberofElementsas parameters and returns the average finally.Line 18–20: Declaring and defining the array and storing the sum of the array in the variable
sum.Line 22: Calling the function
AverageOfArray().
Time complexity
The time complexity to compute the average of an array is
Conclusion
For beginners, it is a best practice to understand basic programming concepts by implementing various functions, such as computing the average and finding the minimum and maximum of an array. These functions help us in statistics.
When calculating the average in C++, why is it important to use floating-point arithmetic for division?
It makes the calculation faster.
It ensures that the division is exact.
It allows for more accurate results with decimals.
It prevents the program from crashing.
Free Resources