Java program to find maximum and minimum number in an array

Java Program to find the maximum and minimum number

In the following question, we are supposed to enter N elements in a dynamic array of size n. After entering into the array, we’ll have to find and print the maximum and minimum element present in the array.

The standard algorithm will be:

  1. Declare a variable N to store the size of the array.
  2. Prompt the user to enter the size of the array and store the input in N.
  3. Declare an array of size N to store the integer inputs.
  4. Declare 2 variables, min_element and max_element, to store the minimum and maximum elements, respectively.
  5. Initialize min_element and max_element with the first element of the array.
  6. Use a loop to iterate over the array, starting from the second element.
  7. Within the loop, compare each element with min_element and max_element. If the current element is less than min_element, update min_element to the current element. If the current element is greater than max_element, update max_element to the current element.
  8. After the loop terminates, print the minimum and maximum elements found, along with a message indicating the result.

Java Code:

import java.util.*;

class ArrMinMax {
    public static void main() {
        Scanner inp = new Scanner(System.in);
        System.out.print("\n Enter Size of Array: ");
        int n = inp.nextInt();
        int i, sum = 0;
        int arr[] = new int[n]; //Creating N-size Array

        for (i = 0; i < n; i++) { //Entering N numbers in array
            System.out.print("\n Enter: ");
            arr[i] = inp.nextInt();
        }

        int max_element = arr[0], min_element = arr[0]; //Initializing with first element.

        for (i = 0; i < n; i++) {
            if (arr[i] > max_element) { //Checking Maximum element
                max_element = arr[i];
            }

            if (arr[i] < min_element) { //Checking Minimum element
                min_element = arr[i];
            }
        }

        //Printing Result
        System.out.println("\n Maximum Number: " + max_element);
        System.out.println("\n Minimum Number: " + min_element);
    }
}

Output:

Enter Size of Array: 6

Enter: 12
Enter: 36
Enter: 5
Enter: 41
Enter: 20
Enter: 36

Maximum Number: 41
Minimum Number: 5
Java program to find maximum and minimum number in an array