Difference between smallest and largest element of an Array

Difference between smallest & largest elements

Display difference between smallest and largest element of an Array

In this java program, we are going to learn how to find the smallest (minimum), largest (maximum) numbers from an array and also find their difference.

The return type of the output is an integer which is the difference between the largest and smallest elements in the array.

import java.util.Scanner;

class MinMaxInArray 
{
    //method to get maximum number from array elements
    int getMax(int[]inputArray)
    {
        int maxValue=inputArray[0];

        for(int i=1;i<inputArray.length;i++)
        {
            if(inputArray[i]>maxValue)
            {
                maxValue=inputArray[i];
            }
        }
        return maxValue;
    }

    //method to get minimum number from array elements
    int getMin(int[]inputArray)
    {
        int minValue=inputArray[0];

        for(int i=1;i<inputArray.length;i++)
        {
            if(inputArray[i]<minValue)
            {
                minValue=inputArray[i];
            }
        }
        return minValue;
    }
}

public class ExArrayDifference
{
    public static void main(String[] args)
    {
        int n;

        // create object of scanner.
        Scanner sc = new Scanner(System.in);

        // you have to enter number here.
        System.out.print("Enter number of elements you wants to enter :" );

        // read entered number and store it in "n".
        n=sc.nextInt();

        int arr[]=new int[n];

        for(int i=0;i<arr.length;i++)
        {
            System.out.print("Enter ["+(i+1)+"] element :" );
            arr[i]=sc.nextInt();
        }

        MinMaxInArray mm=new MinMaxInArray();

        // print max , min , difference of array elements. 
        System.out.println("Maximum value is :" +mm.getMax(arr));
        System.out.println("Minimum value is :" +mm.getMin(arr));
        int Difference=mm.getMax(arr)-mm.getMin(arr);
        System.out.print("Difference between Minnimum and Maximum in array is : " +Difference );	
    }
}

Program Output:

Enter number of elements you wants to enter :6
Enter [1] element :74
Enter [2] element :36
Enter [3] element :58
Enter [4] element :600
Enter [5] element :124
Enter [6] element :70
Maximum value is : 600
Minimum value is :36
Difference between Minimum and Maximum in array is : 564

I hope this post helps you to understand the Difference between the smallest and largest element in an array and its implementation in Java programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *