19 Apr 2024

Find the Minimum and Maximum Value in Array

Minimum and Maximum Value in Array

In this post, we will discuss a simple Java program to find the minimum and maximum values in an array. This program uses straightforward logic to traverse the array, comparing each element to identify the smallest and largest numbers. Let's break it down step-by-step.

import java.util.*;

public class hello(){

        public static void main(String args[]){

int n=sc.nextInt();

int arr[]=new int[n];

int min=Integer.MAX_VALUE;

                int max=Integer.MIN_VALUE;

for(int i=0;i<n;i++){

    arr[i]=sc.nextInt();

    if(arr[i]<min){

        min=arr[i];

    }

                    if(arr[i]>max){

                        max=arr[i];

                    }

}

System.out.print(min+" "+max);

    }

}


How This Program Works

  1. Input Array Size


    int n = sc.nextInt();

    The program first reads the size of the array, n, from the user.

  2. Initialize the Array:

    int arr[] = new int[n];

    An array of size n is created to store the integers.

  3. Set Initial Min and Max:

    int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE;
    • Integer.MAX_VALUE is the largest value an int can hold (2^31 - 1). This ensures that any number in the array will be smaller.
    • Integer.MIN_VALUE is the smallest value an int can hold (-2^31). This ensures that any number in the array will be larger.
  4. Iterate Through the Array: The program loops through all elements in the array using:


    for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); }

    Each element is read and stored in the array. During this loop:

    • If the current element is smaller than min, the program updates min.
    • If the current element is larger than max, the program updates max.
  5. Print Results: Once the loop finishes, the smallest (min) and largest (max) numbers in the array are printed:

    System.out.print(min + " " + max);

Example Input and Output

Input:


5 3 1 9 2 6

Process:

  • Array elements: [3, 1, 9, 2, 6]
  • min starts at Integer.MAX_VALUE and is updated to 3 → 1 (smallest so far).
  • max starts at Integer.MIN_VALUE and is updated to 3 → 9 (largest so far).

Output:


1 9

Key Points

  1. Efficiency:
    • The program only loops through the array once, making it efficient with a time complexity of O(n).
  2. Edge Cases:
    • If all numbers in the array are the same, both min and max will have that value.
    • For an empty array (if n == 0), the program would fail as no inputs would be read. You can add a check for this case.

Improvements

To make this program more robust, you can:

  1. Validate the input size n to ensure it's greater than 0.
  2. Use exception handling to catch invalid inputs.

No comments:

Post a Comment