
STEP 1:
Initial min and max values and set them to 0
int min = 0, max = 0;
STEP 2:
Use for loop to iterate each element in the array
for (int i = 0; i < arr.length; i++)
STEP 3:
Within the loop, write if and else if conditions to compare the current element values and set min/max with current element values
if (arr[i] > max) {
max = arr[i];
} else if (arr[i] < min) {
min = arr[i]; }
Java Program Example:
package TestAutomationCentral;
public class MinMaxArray {
public static void main(String[] args) {
//TestAutomationCentral.com
int arr[] = {45, 56, 850, 5, 54, 551, -2};
int min = 0, max = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
} else if (arr[i] < min) {
min = arr[i];
}
}
System.out.println("Min: " + min + "\nMax: " + max);
}
}
Output:
Min: -2
Max: 850
After following the above tutorials, you can quickly write the code and find an array’s minimum and maximum values. These are commonly asked questions in an interview for Java.