Java Program to find largest and smallest element in array


In this program, You will learn how to find largest and smallest element in array in Java.


List is: 1 2 44 4 5

Largest number is : 44

Smallest number is : 1


Example: How to find largest and smallest element in array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, l = 0, sm = 0;
        int arr[] = new int[5];
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 5 Numbers :");

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

        l = arr[0];
        sm = arr[0];

        for (i = 0; i < 5; i++) {
            if (l < arr[i]) {
                l = arr[i];
            }

            if (sm > arr[i]) {
                sm = arr[i];
            }
        }

        System.out.print("\nThe Largest Element is :" + l);
        System.out.print("\nThe Smallest Element is :" + sm);
    }
}

Output:

Enter 5 Numbers :2 3 1 99 4
The Largest Element is :99
The Smallest Element is :1