JAVA program to find smallest of n numbers in a given array

 

JAVA program to find smallest of n numbers in a given array

This JAVA program is to find the smallest element from a given array.

For example, if an array a consists of elements a={700,81,142,31} and if we want to find the smallest element then the smallest element would be 31.

Logic

We start to iterate and then compare all the elements with each other and store the smallest element in the variable named ‘small’ and then keep comparing till we find the smallest element.

 Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 4

Let us take elements for array a={7,8,12,3}.

small=a[0] i.e. small=7

1st iteration  for(i=1;i<n;i++) i.e.  for(i=1;1<4;i++)

if(a[i]<small)  i.e. if(a[1]<7) i.e. if(8<7) false

2nd iteration  for(i=2;i<n;i++) i.e.  for(i=2;2<4;i++)

if(a[i]<small)  i.e. if(a[2]<7) i.e. if(12<7) false

3rd iteration  for(i=3;i<n;i++) i.e.  for(i=3;3<4;i++)

if(a[i]<small)  i.e. if(a[3]<7) i.e. if(3<7) true

small=a[i] i.e. small=a[3]  i.e. small=3

Now we come out of the for loop as i(4) is not less than n(4)

Hence, the smallest element we found in the array is 3

Program

import java.util.*;

class arr5
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		
	        int i,n,small;
		
		System.out.println("Enter the number of elements:") ;
 		n = sc.nextInt();
		int[] a = new int[n];
 
    		System.out.println("Enter the elements") ;
    		for(i=0;i<n;i++)
    		{
        		a[i] = sc.nextInt();
    		}
		
		small = a[0];		   		
		for(i=1;i<n;i++)
	    	{
			if(a[i]<small)
        		{
				small=a[i];
			}
    		}
    		
		System.out.println("Smallest of "+n+" elements in an array = "+small);
	}
}

Output

Share Me!