Search⌘ K

Solution Review: Find the Maximum Value

Understand how to find the maximum value within a Perl array by iterating through elements and comparing values. Explore array handling, access with @_ , and use of loops to update the maximum value as you process the array elements.

We'll cover the following...

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

Perl
#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.