Open In App

Php Program for Mean of range in array

Last Updated : 13 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Examples : 

Input : arr[] = {1, 2, 3, 4, 5}
        q = 3
        0 2
        1 3
        0 4
Output : 2
         3
         3
Here for 0 to 2 (1 + 2 + 3) / 3 = 2

Input : arr[] = {6, 7, 8, 10}
        q = 2
        0 3
        1 2
Output : 7
         7

Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query.  

PHP




<?php
// PHP program to find floor 
// value of mean in range l to r
  
// To find mean of 
// range in l to r
function findMean($arr, $l, $r)
{
    // Both sum and count 
    // are initialize to 0
    $sum = 0;
    $count = 0;
  
    // To calculate sum and 
    // number of elements in
    // range l to r
    for ($i = $l; $i <= $r; $i++) 
    {
        $sum += $arr[$i];
        $count++;
    }
  
    // Calculate floor 
    // value of mean
    $mean = floor($sum / $count);
  
    // Returns mean of array
    // in range l to r
    return $mean;
}
  
// Driver Code
$arr = array(1, 2, 3, 4, 5);
echo findMean($arr, 0, 2), "
";
echo findMean($arr, 1, 3), "
";
echo findMean($arr, 0, 4), "
";
  
// This code is contributed by ajit
?>


Output : 

2
3
3

Time Complexity: O(n)

Please refer complete article on Mean of range in array for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads