Problem: 4.2


 Question 4.2: Write a program in Java to find the second smallest element in an array.
Input the size of array : 5
Input 5 elements in the array (value must be <9999) :
element - 0 : 0
element - 1 : 9
element - 2 : 4
element - 3 : 6
element - 4 : 5
Expected Output :
The Second smallest element in the array is : 4


Solution: 


package lab4problem2;

import java.util.Scanner;

public class Lab4Problem2 {


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Input the size of array : ");

        int size = input.nextInt();

        int array[]=new int[size];

        int total = 0;

        for (int i = 0; i < size; i++) {

            System.out.print("element - " + i + " : ");

            array[i] = input.nextInt();

            total = total * 10 + array[i];

        }

        if (total < 9999) {

            int temp = 0;

            for (int i = size; i > 1; i--) {

                for (int j = 1; j < size; j++) {

                    if (array[j - 1] > array[j]) {

                        temp = array[j - 1];

                        array[j - 1] = array[j];

                        array[j] = temp;

                    }

                }

            }

            System.out.println("The Second smallest element in the array is : " + array[1]);

        }

        else

            System.out.println("Enter valid number!");

    }

}


Previous Post Next Post