JAVA SP T


Lets dive into snapshot of my programs!💻

19.Program to Find 2nd Smallest Number in an array.

💡Code:

  
                public class SecondSmallestNumber7078 {
                    public static void main(String[] args) {
                        // Example array
                        int[] array = {5, 2, 8, 1, 9, 3, 6};
                
                        // Display the original array
                        System.out.println("Original Array:");
                        displayArray(array);
                
                        // Find the second smallest number
                        int secondSmallest = findSecondSmallest(array);
                
                        // Display the result
                        System.out.println("\nSecond Smallest Number: " + secondSmallest);
                    }
                
                    // Method to find the second smallest number in an array
                    private static int findSecondSmallest(int[] arr) {
                        int smallest = Integer.MAX_VALUE;
                        int secondSmallest = Integer.MAX_VALUE;
                
                        for (int value : arr) {
                            if (value < smallest) {
                                secondSmallest = smallest;
                                smallest = value;
                            } else if (value < secondSmallest && value != smallest) {
                                secondSmallest = value;
                            }
                        }
                
                        return secondSmallest;
                    }
                
                    // Method to display the elements of an array
                    private static void displayArray(int[] arr) {
                        for (int value : arr) {
                            System.out.print(value + " ");
                        }
                        System.out.println();
                    }
                }
                

               

📸Output :

output