TutorialStudyMite

Java program to find maximum and minimum number in an array

Beginner friendly

Track completion, mastery, and revision.

Java Program to Find Maximum and Minimum Numbers in an Array

Problem Statement

Write a Java program that accepts N integer elements from the user, stores them in an array, and finds both the maximum and minimum values in the array.

Algorithm

1. Read the size of the array N from the user

2. Create an integer array of size N

3. Read N integers from the user and store them in the array

4. Initialize two variables:

   - max_element with the first array element

   - min_element with the first array element

5. Iterate through the array starting from the second element:

   - Update max_element if current element is larger

   - Update min_element if current element is smaller

6. Display both maximum and minimum values

Java Implementation

import java.util.Scanner;

public class ArrayMinMax {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read array size
        System.out.print("Enter the size of the array: ");
        int n = scanner.nextInt();
        
        // Input validation
        if (n <= 0) {
            System.out.println("Array size must be a positive integer.");
            return;
        }
        
        int[] numbers = new int[n];
        
        // Read array elements
        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            System.out.print("Enter element " + (i + 1) + ": ");
            numbers[i] = scanner.nextInt();
        }
        
        // Initialize min and max with first element
        int maxElement = numbers[0];
        int minElement = numbers[0];
        
        // Find min and max
        for (int i = 1; i < n; i++) {
            if (numbers[i] > maxElement) {
                maxElement = numbers[i];
            }
            if (numbers[i] < minElement) {
                minElement = numbers[i];
            }
        }
        
        // Display results
        System.out.println("\nResults:");
        System.out.println("Maximum number: " + maxElement);
        System.out.println("Minimum number: " + minElement);
        
        scanner.close();
    }
}

Sample Output

Enter the size of the array: 6
Enter 6 integers:
Enter element 1: 12
Enter element 2: 36
Enter element 3: 5
Enter element 4: 41
Enter element 5: 20
Enter element 6: 36

Results:
Maximum number: 41
Minimum number: 5

Time Complexity

  • Time: O(n) - Single pass through the array

  • Space: O(n) - Storage for the array elements

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.