w3resource

PHP Exercises: Find the larger average value between the first and the second half of a given array of integers and minimum length is atleast 2

PHP Basic Algorithm: Exercise-132 with Solution

Write a PHP program to find the larger average value between the first and the second half of a given array of integers and minimum length is atleast 2. Assume that the second half begins at index (array length)/2.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{ 
    // Calculate the average of the first half of the array using the 'Average' function
    $firstHalf = Average($numbers, 0, sizeof($numbers) / 2);
    
    // Calculate the average of the second half of the array using the 'Average' function
    $secondHalf = Average($numbers, sizeof($numbers) / 2, sizeof($numbers));

    // Return the larger of the two averages
    return $firstHalf > $secondHalf ? $firstHalf : $secondHalf;
}  

// Define a function named 'Average' that calculates the average of a specified range within an array
function Average($num, $start, $end)
{
    // Initialize a variable to store the sum of elements in the specified range
    $sum = 0;

    // Iterate through the specified range and calculate the sum of elements
    for ($i = $start; $i < $end; $i++)
        $sum += $num[$i];

    // Return the average of the specified range
    return $sum / (sizeof($num) / 2);
}  

// Use the 'echo' statement to print the result of the 'test' function for different arrays
echo test([1, 2, 3, 4, 6, 8]) . "\n";
echo test([15, 2, 3, 4, 15, 11]) . "\n";
?>

Sample Output:

6
10

Flowchart:

Flowchart: Find the larger average value between the first and the second half of a given array of integers and minimum length is atleast 2.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check a given array (length will be atleast 2) of integers and return true if there are two values 15, 15 next to each other.
Next: Write a PHP program to count the number of strings with given length in given array of strings.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-132.php