second smallest element using single loop

To find the second smallest element in an array using a single loop in C++, you can follow these steps:

  1. Declare and initialize two variables, smallest and secondSmallest, with the maximum possible value of the data type you are working with. This ensures that any element in the array will be smaller than these initial values.
int smallest = INT_MAX;
int secondSmallest = INT_MAX;
  1. Iterate over the array using a for loop. Compare each element with the current smallest and secondSmallest values.
for (int i = 0; i < arraySize; i++) {
    if (array[i] < smallest) {
        secondSmallest = smallest;
        smallest = array[i];
    } else if (array[i] < secondSmallest && array[i] != smallest) {
        secondSmallest = array[i];
    }
}
  1. Inside the loop, check if the current element is smaller than the smallest value. If it is, update both smallest and secondSmallest accordingly. If the current element is not smaller than smallest, but smaller than secondSmallest and not equal to smallest, update only secondSmallest.

  2. After the loop finishes executing, the variable secondSmallest will hold the second smallest element in the array.

Here's the complete code snippet:

#include <iostream>
#include <climits>

int main() {
    int array[] = {5, 3, 8, 1, 9, 2};
    int arraySize = sizeof(array) / sizeof(array[0]);

    int smallest = INT_MAX;
    int secondSmallest = INT_MAX;

    for (int i = 0; i < arraySize; i++) {
        if (array[i] < smallest) {
            secondSmallest = smallest;
            smallest = array[i];
        } else if (array[i] < secondSmallest && array[i] != smallest) {
            secondSmallest = array[i];
        }
    }

    std::cout << "The second smallest element is: " << secondSmallest << std::endl;

    return 0;
}

This code will output: The second smallest element is: 2.

Note: The code assumes that the array contains at least two elements. If the array has fewer than two elements, the code may produce incorrect results.