How to get difference of minimum and maximum array element ?
The blog provides the technical approach on ” How to get difference of minimum and maximum array element ?”
Problem Statement:
How to identify the minimum array element, maximum array element and difference of minimum and maximum array elements in java
Technical Approach:
- Get the Array Count as User Input
- Get the Array Elements as User Input
- Iterate the Array Elements
- Compare Array Elements to get the minimum element
- Compare Array Elements to get the maximum element
- Calculate the difference of minimum and maximum element
package com.java.planforexams.array; import java.util.Scanner; public class DiffBWMinMaxArrayElement { public static void main(String[] args) { // Scanner object for reading User Input Scanner scan = new Scanner(System.in); int count; int minArrayElement =0; int maxArrayElement =0; // Receive the Array Element Count from User System.out.print("Provide the Array Element Count : "); // Get the Array Count count = scan.nextInt(); //Set the Array Size with Count value int arrayInputFromUser[] = new int[count]; // Receive the Array Elements from User. System.out.println("Enter the elements:"); // Iterate the array elements for (int incr=0; incr<count; incr++) { arrayInputFromUser[incr] = scan.nextInt(); } minArrayElement=arrayInputFromUser[0]; maxArrayElement=arrayInputFromUser[0]; for(int i=1;i<count;i++) { if(arrayInputFromUser[i]>maxArrayElement) { maxArrayElement=arrayInputFromUser[i]; } if(arrayInputFromUser[i]<minArrayElement) { minArrayElement=arrayInputFromUser[i]; } } System.out.println("Minimum Array element is :" + minArrayElement); System.out.println("Maximum Array Element is :" + maxArrayElement); int arrayElmentDiff = maxArrayElement -minArrayElement ; System.out.print("Difference between Minimum and Maximum in array is : " + arrayElmentDiff); } } Output: Provide the Array Element Count : 5 Enter the elements: 12 12 32 32 34 Minimum Array element is :12 Maximum Array Element is :34 Difference between Minnimum and Maximum in array is : 22
Leave a Reply