How To Find Max and Min Value in an Array - Java
Finding maximum and minimum number in an array is pretty easy.
In this simple tutorial we'll just create two functions, one for finding maximum number and the other for finding minimum number.!
The first function: finding maximum number
int max = arr[0];
for(int a: arr) {
if (a > max)
max = a;
}
return max;
}
The function above takes an array as argument, then declare a variable max and set it to the value of the first element in the array.
Then we use an enhanced for-loop to loop through all the elements of the array checking to see if a specific element is greater than the value of max, if we found one, then reset the value of max.
Keep doing this until all elements are checked.
The second function: finding minimum number
int min = arr[0];
for (int a: arr) {
if (a < min)
min = a;
}
return min;
}
The above function is exactly the opposite of the first one but instead of finding the greater number we find the smaller one.
Full code
public static void main(String[] args) {
int arr[] = {23, 2, 4, 67, 3, 4, 9};
System.out.println(getMax(arr));
System.out.println(getMin(arr));
}
public static int getMax(int []arr) {
int max = arr[0];
for(int a: arr) {
if (a > max)
max = a;
}
return max;
}
public static int getMin(int []arr) {
int min = arr[0];
for (int a: arr) {
if (a < min)
min = a;
}
return min;
}
}