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:
- Initialize the Array: Define an array of integers and the size of the array.
- Initialize Variables: Set two variables,
first
andsecond
, toINT_MAX
to store the first and second smallest elements. - Iterate Through the Array: Use a single loop to iterate through the array.
- Update
first
andsecond
: Updatefirst
andsecond
based on the current element being iterated. - Output Result: Output the second smallest element after the loop. If
second
is stillINT_MAX
, it means there is no second smallest element in the array.