how to find second smallest element in an array using single loop

Code to Find Second Smallest Element in an Array Using Single Loop in C++

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 5, 8, 3, 9, 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int first = INT_MAX, second = INT_MAX;

    for (int i = 0; i < n; i++) {
        if (arr[i] < first) {
            second = first;
            first = arr[i];
        } else if (arr[i] < second && arr[i] != first) {
            second = arr[i];
        }
    }

    if (second == INT_MAX) {
        cout << "There is no second smallest element" << endl;
    } else {
        cout << "The second smallest element is: " << second << endl;
    }

    return 0;
}

Explanation:

  1. Initialize the Array: Define an array of integers and the size of the array.
  2. Initialize Variables: Set two variables, first and second, to INT_MAX to store the first and second smallest elements.
  3. Iterate Through the Array: Use a single loop to iterate through the array.
  4. Update first and second: Update first and second based on the current element being iterated.
  5. Output Result: Output the second smallest element after the loop. If second is still INT_MAX, it means there is no second smallest element in the array.