Write a Java program to find the maximum and minimum elements in an array.
public class MaxMinArray {
public static void findMaxMin(int[] arr) {
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
}
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 7};
findMaxMin(numbers);
}
}
Comments
Post a Comment