Solution Review: Find the Maximum Value
In this review, solution of the challenge 'Find the Maximum Value' from the previous lesson is provided.
We'll cover the following...
We'll cover the following...
Solution
Press + to interact
Java
class CheckMax {//Returns maximum value from Array passed as parameterpublic static int findMaxVal(int[] arr) {int max = arr[0];for (int i = 1; i < arr.length; i++) { //iterate over all the array elementsif (arr[i] > max) { //check if current element is greater than the already//stored max valuemax = arr[i]; // if yes then update the max value to current element}}return max; //return the maximum value} //end of findMaxValue()//end of CheckMaxpublic static void main( String args[] ) {int array [] = {78, 89, 32, 90, 21};System.out.println( "The maximum value in an array is: "+findMaxVal(array));}}
How does the above code work?
-
Line 5: We start by declaring an
max
variable and storing the first element of ...