C++ Programming: Finding the Second Smallest Element in an Array | Step-by-Step Algorithm

preview_player
Показать описание
Learn how to find the smallest element in a array in a very easy way. The code is provided.
Рекомендации по теме
Комментарии
Автор

The code is here
#include <bits\stdc++.h>
using namespace std;



int findSecondSmallest(int arr[], int size) {
int min1 = INT_MAX;
int min2 = INT_MAX;

for (int i = 0; i < size; ++i) {
if (arr[i] < min1) {
min2 = min1;
min1 = arr[i];
} else if (arr[i] < min2 && arr[i] > min1) {
min2 = arr[i];
}
}

return min2;
}

int main() {
int arr[] = { 9, 5, 2, 8, 1, 10 };
int size = sizeof(arr) / sizeof(arr[0]);

int secondSmallest = findSecondSmallest(arr, size);

if (secondSmallest != INT_MAX) {
cout << "The second smallest element is: " << secondSmallest << endl;
} else {
cout << "No second smallest element found." <<endl;
}

return 0;
}

LearnCodingWithQasim
visit shbcf.ru