Java Program to find the largest and smallest element in the array


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


List is: 1 2 44 4 5

The largest number is: 44

The smallest number is: 1

Example: How to find the largest and smallest element in the array in java.

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.println("Largest element:" + l);
        System.out.println("Smallest element:" + sm);
    }
}

Output:

Enter 5 numbers:20 10 30 50 40
Largest element:50
Smallest element:10