Q:

Java program to find differences between minimum and maximum numbers in an array

belongs to collection: Java Array Programs

0

Given an array, we have to find the minimum, maximum numbers and their difference of them using java program.

Example:

    Input:  10 20 30 40 50
    Minimum number: 10
    Maximum number: 50
    Differences of minim and maximum number: (50-10) = 40

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to find difference of minimum and maximum numbers of array in java

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);
  }
}

Output

    Enter number of elements you wants to enter :10
    Enter [1] element :25
    Enter [2] element :36
    Enter [3] element :74
    Enter [4] element :85
    Enter [5] element :964
    Enter [6] element :215
    Enter [7] element :36
    Enter [8] element :58
    Enter [9] element :98
    Enter [10] element :123
    Maximum value is :964
    Minimum value is :25
    Difference between Minnimum and Maximum in array is : 939

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to move all zero at the end of the ar... >>
<< Java program to find average of all array elements...