Smallest element of an array

Smallest element of an array

Java program to display smallest element of an array

This is a Java Program to Find the Smallest Elements in an Array.

Enter the size of the array and then enter all the elements of that array. Now with the help of for loop and min variable, we sort the array in ascending order.
Here is the source code of the Java Program to Find the Smallest Elements in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;
public class ExArrayFindMinimum
{
    public static void main(String[] args) 
    {
    	// Intialising the variables
        int n, min;
        Scanner Sc = new Scanner(System.in);
        
        // Enter the number of elements.
        System.out.print("Enter number of elements : ");
        n = Sc.nextInt();
        
        // creating an array.
        int a[] = new int[n];
        
        // enter array elements.
        System.out.println("Enter the elements in array : ");
        for (int i = 0; i < n; i++) 
        {
            a[i] = Sc.nextInt();
        }
        
        for (int i = 0; i < n; i++) 
        {
            for (int j = i + 1; j < n; j++) 
            {
                if (a[i] > a[j]) 
                {
                    min = a[i];
                    a[i] = a[j];
                    a[j] = min;
                }
            }
        }
        System.out.println("The Smallest element in the array is :"+a[0]);
    }
}

Program Output:

Enter number of elements : 5
Enter the elements in array : 
12
40
67
25
14
The Smallest element in the array is :12

I hope this post helps you to understand how to find smallest element in the array and its implementation in Java programming language.

Keep coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *