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,

  • NN is the total number of elements in an array.

  • aia_i represents the element at the ithi^{th}index.

  • AA represents the average of an array.

  • i=0nai\sum_{i=0}^{n} a_i 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.

Array
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 the sum of the array and TotalNumberofElements as 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 O(n)O(n).

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.

Q

When calculating the average in C++, why is it important to use floating-point arithmetic for division?

A)

It makes the calculation faster.

B)

It ensures that the division is exact.

C)

It allows for more accurate results with decimals.

D)

It prevents the program from crashing.

Copyright ©2024 Educative, Inc. All rights reserved