September 2019
Intermediate to advanced
816 pages
18h 47m
English
Computing the maximum value of an array of numbers can be implemented by looping the array and tracking the maximum value via a comparison with each element of the array. In terms of lines of code, this can be written as follows:
public static int max(int[] arr) { int max = arr[0]; for (int elem: arr) { if (elem > max) { max = elem; } } return max;}
A little pinch in readability here may entail using the Math.max() method instead of an if statement:
...max = Math.max(max, elem);...
Let's suppose that we have the following array of integers and a utility class named MathArrays that contains the preceding methods:
int[] integers = {2, 3, 4, 1, -4, 6, 2};
The maximum of this array can easily be obtained as follows: ...