Question: The script below is to compute the maximum, minimum, average, and sum of elements in an array in php. Although the script runs, it does
The script below is to compute the maximum, minimum, average, and sum of elements in an array in php. Although the script runs, it does not output the correct values. To get it to work, you will need to implement the following two functions:
- getMax($array) - This method should return the maximum of the elements in the array.
- getSum($array) - This method should return the sum of the elements in the array.
- Now change the script to instead use command line arguments to read in the list of numbers directly from the command line.
PHP supports command line arguments by providing a built-in array, $argv which is 0-indexed. Note: the first element in this array is the script's name, so you will need to process starting from index 1.
| function getMin($array) { | |
| if($array == null || count($array) == 0) { | |
| return null; | |
| } | |
| $min = $array[0]; | |
| for($i=1; $i | |
| if($min > $array[$i]) { | |
| $min = $array[$i]; | |
| } | |
| } | |
| return $min; | |
| } | |
| function getMax($array) { | |
| //TODO: implement this function | |
| return null; | |
| } | |
| function getAverage($array) { | |
| if($array == null) { | |
| return null; | |
| } | |
| $sum = getSum($array); | |
| return ($sum / count($array)); | |
| } | |
| function getSum($array) { | |
| //TODO: implement this function | |
| return null; | |
| } | |
| echo "Please input the number of integers being entered (>=2): "; | |
| /* variable identifiers begin with the dollar sign | |
| as PHP is weakly typed, no type needs to be declared | |
| */ | |
| $numberOfEntries = intval(trim(fgets(STDIN))); | |
| if($numberOfEntries < 2) { | |
| print "Invalid input: number of entries must be at least 2 "; | |
| exit(1); | |
| } | |
| $numbers = array(); | |
| echo "Enter your integers one at at time, followed by the enter key. "; | |
| $count = 0; | |
| while($count < $numberOfEntries) { | |
| /* standard input can be scanned with fgets | |
| elements can be appended using the following syntax | |
| */ | |
| $numbers[] = intval(trim(fgets(STDIN))); | |
| $count++; | |
| } //end of for loop | |
| $min = getMin($numbers); | |
| $max = getMax($numbers); | |
| $average = getAverage($numbers); | |
| $sum = getSum($numbers); | |
| /* | |
| Output can be done with echo, print, or printf, string concatenation is done | |
| with the period operator. | |
| */ | |
| echo "The sum is ".$sum." "; | |
| echo "The average is ".$average." "; | |
| echo "The highest is ".$max." "; | |
| echo "The lowest is ".$min." "; | |
| ?> |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
