Mean of range in array in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of n integers. You are given q queries. Write a program to print floor value of mean in range l to r for each query in a new line

If given input array is arr[] = {1, 2, 3, 4, 5} and queries are −

q = 3
(0 2)
(1 3)
(0 4)
Then output will be −
2
3
3
Here for 0 to 2 (1 + 2 + 3) / 3 = 2

Algorithm

1. Run loop for each query l to r and find sum and number of elements in range.
2. Print floor of mean for each query

Example

#include <bits/stdc++.h>
using namespace std;
int findMean(int *arr, int l, int r){
   int sum = 0, count = 0;
   for (int i = l; i <= r; ++i) {
      sum += arr[i];
      count++;
   }
   int mean = floor(sum / count);
   return mean;
}
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   cout << "Result:\n";
   cout << findMean(arr, 0, 2) << endl;
   cout << findMean(arr, 1, 3) << endl;
   cout << findMean(arr, 0, 4) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Result:
2
3
3
raja
Published on 10-Feb-2020 10:09:42
Advertisements