Finding the range of all elements in an array
Hint: Find out max and min number first.
Then range = max – min
Here’s a Java program that finds the range of all elements in an array:
public class ArrayRange { public static void main(String[] args) { int[] array = {10, 5, 3, 8, 15, 7, 2, 12}; // Finding the range of the array int min = array[0]; int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } if (array[i] > max) { max = array[i]; } } int range = max - min; System.out.println("Minimum value: " + min); System.out.println("Maximum value: " + max); System.out.println("Range: " + range); } }
In this program, we initialize an array of integers with some values. We then iterate through the array to find the minimum and maximum values. Finally, we calculate the range by subtracting the minimum from the maximum. The program outputs the minimum value, maximum value, and the range of the array.
When you run the program, you should see the following output:
Minimum value: 2
Maximum value: 15
Range: 13
This means that the minimum value in the array is 2, the maximum value is 15, and the range is 13.
No comments yet! You be the first to comment.