Smallest and largest number in an array in JAVA programming


import java.util.Scanner;

public class LargestandSmallest {

    public static void main(String[] args) {
        Scanner myScanner=new Scanner(System.in);
       
        int n;
        int[] arr=new int[100];
        System.out.print("Enter the number of elements : ");
        n=myScanner.nextInt();
        System.out.print("Enter "+n+" numbers : ");
        for (int i = 0; i < n; i++) {
            arr[i]=myScanner.nextInt();
        }
        int small,large;
        small=arr[0];
        large=arr[0];
        for (int i = 0; i < n; i++) {
            if (small>arr[i]) {
                small=arr[i];
            }
            else if(large<arr[i]){
                large=arr[i];
            }
        }
        System.out.print("Smallest number is : "+small);
        System.out.println();
        System.out.print("Largest number is : "+large);
    }

}

Share this

Related Posts

Previous
Next Post »