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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.