Write a program to find the second smallest element in an array


This is a Java program that takes an integer array input from the user and finds the second smallest number in the array. Here is a brief explanation of the code:

  • The program imports the Scanner class from the java.util package to read input from the user.
  • The program defines a static method called SecondSmallest that takes an integer array a and its length len as input.
  • The SecondSmallest method uses a nested for loop to compare each element of the array with all the other elements to sort the array in ascending order.
  • After sorting the array, the method returns the second element (i.e., a[1] ) as the second smallest number in the array.
  • The main method first reads the length of the array from the user and creates an array of that size.
  • It then prompts the user to enter the elements of the array and stores them in the array using a for loop.
  • Finally, the main method calls the SecondSmallest method to find the second smallest number in the array and prints it to the console.

Source Code

import java.util.Scanner;
class Array_Second_Smallest
{  
	public static int SecondSmallest(int[] a, int len){  
	int t;  
	for (int i = 0; i < len; i++)   
		{  
			for (int j = i + 1; j < len; j++)   
			{  
				if (a[i] > a[j])   
				{  
					t = a[i];  
					a[i] = a[j];  
					a[j] = t;  
				}  
			}  
		}  
	   return a[1]; 
	}  
	public static void main(String args[])
	{  
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
        for(int i=0;i<l;i++)
        {
            System.out.printf("Element of a[%d] :",i);
            a[i]=input.nextInt();
        }
		System.out.println("Second Smallest Number is : "+SecondSmallest(a,l)); 
	}
}  

Output

Enter the Array Limit :5
Element of a[0] :10
Element of a[1] :20
Element of a[2] :5
Element of a[3] :2
Element of a[4] :30
Second Smallest Number is : 5

Example Programs