Finding the maximum or minimum element in an array.
Here’s an example Java program that finds the maximum and minimum elements in an array:
public class ArrayMinMax { public static void main(String[] args) { int[] numbers = {5, 2, 9, 1, 7, 3}; // Finding the maximum element int max = numbers[0]; // Assume the first element is the maximum for (int i = 1; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } } System.out.println("Maximum element: " + max); // Finding the minimum element int min = numbers[0]; // Assume the first element is the minimum for (int i = 1; i < numbers.length; i++) { if (numbers[i] < min) { min = numbers[i]; } } System.out.println("Minimum element: " + min); } }
In this program, we have an array called `numbers` with some integer values. We use two variables, `max` and `min`, to store the maximum and minimum elements respectively.
To find the maximum element, we assume the first element is the maximum and then iterate through the array. If we find a number greater than the current maximum, we update the `max` variable with that number.
Similarly, to find the minimum element, we assume the first element is the minimum and iterate through the array. If we find a number smaller than the current minimum, we update the `min` variable with that number.
Finally, we print the maximum and minimum elements using `System.out.println()`. When you run this program, it will output the maximum and minimum elements in the given array:
Maximum element: 9
Minimum element: 1