Find The Difference Between The Largest And Smallest Values In An Array Of Integers | Java Programs

Output:

*** Difference Between Largest And Smallest Number In Array ***

Original Array: [5, 7, 2, 4, 9]
The Largest Number is: 9
The Smallest Number is: 2
Difference between the largest and smallest values of array: 7

Click Here For Java Online Compiler

Solution:

import java.util.Arrays;

public class DifferenceLargestSmallest {

    public static void main(String[] args) {
        int[] array = {5, 7, 2, 4, 9};
        System.out.println("*** Difference Between Largest And Smallest Number In Array ***" + "\n");
        System.out.println("Original Array: " + Arrays.toString(array));
        int max = array[0];
        int min = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            } else if (array[i] < min) {
                min = array[i];
            }
        }
        System.out.println("The Largest Number is: " + max);
        System.out.println("The Smallest Number is: " + min);
        System.out.println("Difference between the largest and smallest values of array: " + (max - min));
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon