Google News
logo
C++ Program to Find Second Smallest Element in an Array
In the following example of C++ program to find the second smallest element in an array :
Program :
#include <iostream>
#include <limits>

int main() {
    const int SIZE = 5;
    int arr[SIZE];
    std::cout << "Enter " << SIZE << " integers: ";
    for (int i = 0; i < SIZE; i++) {
        std::cin >> arr[i];
    }
    int smallest = arr[0];
    int secondSmallest = std::numeric_limits<int>::max();
    for (int i = 1; i < SIZE; i++) {
        if (arr[i] < smallest) {
            secondSmallest = smallest;
            smallest = arr[i];
        }
        else if (arr[i] < secondSmallest && arr[i] != smallest) {
            secondSmallest = arr[i];
        }
    }
    if (secondSmallest == std::numeric_limits<int>::max()) {
        std::cout << "There is no second smallest element in the array." << std::endl;
    }
    else {
        std::cout << "The second smallest element in the array is " << secondSmallest << std::endl;
    }
    return 0;
}
Output :
Enter 5 integers: 9
6
3
12
4
The second smallest element in the array is 4
* This program creates an array arr of size SIZE (which is set to 5 in this example), and prompts the user to enter SIZE integers. It then uses a for loop to iterate over each element of the array, and stores the input in the corresponding element.

* The program then initializes two variables, smallest and secondSmallest, to the first element of the array arr[0] and the maximum value of an integer, respectively. It then uses another for loop to iterate over each element of the array starting from the second element arr[1].

* For each element arr[i], the program checks whether it is smaller than smallest. If it is, the program updates secondSmallest to the old value of smallest, and smallest to the new value of arr[i]. If arr[i] is not smaller than smallest, the program checks whether it is smaller than secondSmallest and not equal to smallest. If it is, the program updates secondSmallest to the new value of arr[i].

* After the loop completes, secondSmallest will contain the second smallest element in the array. If there is no second smallest element in the array, secondSmallest will be equal to std::numeric_limits<int>::max(). Finally, the program outputs the second smallest element to the console using std::cout.