Mean of range in array in C++

In this problem, we are given an array of n integers and some m querries. Our task is to create a program that calculates the integral value(round down) of the mean of the ranges given by the querries.

Let’s take an example to understand the problem,


array = {5, 7, 8, 9, 10}
m = 2; [0, 3], [2, 4]



To solve this problem, we have two methods one is direct and the other is using prefix sum.

In the direct approach, for each query, we will loop from the start index to the end index of the range. And add all integers of the array and divide by count. This approach works fine and prints the result but is not an effective one.

Using prefixSum

In this approach, we will calculate the prefix sum array which will store the sum of all elements of the array till the ith index i.e. prefixSum(4) is the sum of all elements till index 4.

Now, using this prefixSum array we will calculate the mean for each query using the formula,

Mean = prefixSum[upper] - prefixSum(lower-1) / upper-lower+1

Upper and lower are the indexes given in the query. If lower = 0, prefixSum(lower-1) = 0.


Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
#define MAX 100
using namespace std;
int prefixSum[MAX];
void initialisePrefixSum(int arr[], int n) {
   prefixSum[0] = arr[0];
   for (int i = 1; i < n; i++)
   prefixSum[i] = prefixSum[i - 1] + arr[i];
int queryMean(int l, int r) {
   int mean;
   if (l == 0)
      mean =(prefixSum[r]/(r+1));
      mean =((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));
      return mean;
int main() {
   int arr[] = {5, 7, 8, 9, 10 };
   int n = sizeof(arr) / sizeof(arr[0]);
   initialisePrefixSum(arr, n);
   cout<<"Mean in 1st query: "<<queryMean(1, 4)<<endl;
   cout<<"Mean in 2st query: "<<queryMean(2, 4)<<endl;
   return 0;


Mean in 1st query: 8
Mean in 2st query: 9

Updated on: 03-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started