Write a c program to find the second smallest element in an integer array.
#include <stdio.h>
#include <limits.h>
int main() {
int arr[] = {1,1,1,1,1,1};
//int arr[] = {9,5,2,8,1};
int size = sizeof(arr) / sizeof(arr[0]);
int smallest = INT_MAX;
int secondSmallest = INT_MAX;
for (int i = 0; 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 == INT_MAX) {
printf("No second smallest element found.\n");
}
else {
printf("Second smallest element: %d\n", secondSmallest);
}
return 0;
}
output: No second smallest element found.
//OutPUT : Second smallest element: 2
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter