How to find minimum and maximum numbers in a Java array

By IncludeHelp Last updated : February 4, 2024

An array is a set of the same type of data types, it can contain any number of elements of the same type. In this tutorial, we will learn how can we find the maximum and minimum numbers from a given array.

Problem statement

Given an array of integers, write a Java program to find the minimum and maximum numbers from the given array.

Examples

Consider the below examples with sample input and output:

Array elements: 111, 222, 333, 444, 555, 108, 11
Minimum number: 11
Maximum number: 555

Array elements: 10, 11, 2, 10
Minimum number: 2
Maximum number: 10

Finding Minimum and Maximum Numbers in a Java Array

To find the minimum and maximum number in an array, use a simple loop, iterate its elements, and keep track of the minimum/maximum value by using the conditional statement.

Pseudo code to find the minimum number

public int minimumNumber(int[] arr) {
int min = arr[0];

for (int i = 0; i < arr.length; i++) {
  if (arr[i] < min) {
    min = arr[i];
  }
}
return min;
}

Pseudo code to find the maximum number

public int maximumNumber(int[] arr) {
int max = 0;

for (int i = 0; i < arr.length; i++) {
  if (arr[i] > max) {
    max = arr[i];
  }
}
return max;
}

Java program to find minimum and maximum numbers in an Array

In this program, we have an array (arr) and find its minimum (smallest) and maximum (largest) numbers.

// Java code to find minimum and maximum numbers 
// in a Java Array
public class Main {
  // Method to find minimum number 
  public int minimumNumber(int[] arr) {
    int min = arr[0];

    for (int i = 0; i < arr.length; i++) {
      if (arr[i] < min) {
        min = arr[i];
      }
    }
    return min;
  }

  // Method to find maximum number 
  public int maximumNumber(int[] arr) {
    int max = 0;

    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > max) {
        max = arr[i];
      }
    }
    return max;
  }

  // The main() method
  public static void main(String args[]) {
    // Creating an array of integers
    int[] arr = {
      111,
      222,
      333,
      444,
      555,
      108,
      11
    };

    // Creating object of Main class 
    // to call the methods
    Main obj = new Main();
    System.out.println("Minimum number in the array is : " +
      obj.minimumNumber(arr));
    System.out.println("Maximum number in the array is : " +
      obj.maximumNumber(arr));
  }
}

Output

The output of the above program is:

Minimum number in the array is : 11
Maximum number in the array is : 555

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.