Array-promo

Question

Print second smallest in an array.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class secondSmallestElementInAnArray
{  
    public static void main(String[] args)
    {  
        /* Initialize array */  
        int [] arr1;
        
        int n=0,i=0,min=0,ss=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter a no. of elements in the array");   
        n = sc.nextInt(); 
        System.out.println("Enter numbers in array");
        arr1=new int[n];
        for(i=0;i< n;i++)
        {
            arr1[i]=sc.nextInt();
        }
        min=arr1[0];
        ss=arr1[0];
        System.out.println();  
          
        
        for ( i = 0; i < n; i++) 
        {   
            if(arr1[i]< min)
            {
                min=arr1[i];
            }
            if(arr1[i]< ss && arr1[i]> min)
            {
                ss=arr1[i];
            }
        }  
        System.out.println("Second Smallest element in the array is "+ss); 
    }  
}    

				
			

Coding Store

10-minute Stress-Buster Games

Leave a Reply

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