Solution Review: Find the Maximum Value

Let's go over the solution review of the challenge given in the previous lesson.

We'll cover the following

Let’s look at the solution first before jumping into the explanation:

Press + to interact
#Returns maximum value from Array passed as parameter
sub Find_Maximum {
my @list = @_;
$max = $list[0];
for ($i = 1; $i <= $#list; $i++) { #iterate over all the array elements
if ($list[$i] > $max) { #check if current element is greater than the already
#stored max value
$max = $list[$i]; # if yes then update the max value to current element
}
}
return $max; #return the maximum value
}#end of Find_Maximum()
@array = (15, 6, 3, 21, 19, 4);
print Find_Maximum (@array);

Explanation

We access the array passed from the main function by using @_ and store it in an array list. $max is set equal to the first element of the array (stored at index 0) for comparison to other array elements. The for loop starts from index 1 and runs till the last index of the array. In each iteration, it compares $list[$i] with $max. If the $list[$i] element is greater than $max, then $max is updated to the current element of the array being compared. At the end of the for loop, $max contains the maximum value in the array and is returned.