C Online Compiler
Example: Find Second Smallest Element in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Second Smallest Element #include <stdio.h> #include <limits.h> // Required for INT_MAX int main() { int arr[] = {12, 3, 1, 9, 5, 10, 1}; // Example array with a duplicate int n = sizeof(arr) / sizeof(arr[0]); // Step 1: Initialize firstSmallest and secondSmallest // We initialize them to INT_MAX (the largest possible integer value) // This ensures that any element in the array will be smaller than them. int firstSmallest = INT_MAX; int secondSmallest = INT_MAX; // Step 2: Handle edge cases for array size if (n < 2) { printf("Array should have at least two elements.\n"); return 1; // Indicate an error or invalid input } // Step 3: Iterate through the array for (int i = 0; i < n; i++) { // If current element is smaller than firstSmallest if (arr[i] < firstSmallest) { // The old firstSmallest becomes the new secondSmallest secondSmallest = firstSmallest; // The current element becomes the new firstSmallest firstSmallest = arr[i]; } // Else if current element is smaller than secondSmallest // AND it's not equal to firstSmallest (to handle duplicates) else if (arr[i] < secondSmallest && arr[i] != firstSmallest) { // The current element becomes the new secondSmallest secondSmallest = arr[i]; } } // Step 4: Check if secondSmallest was found // If secondSmallest is still INT_MAX, it means all elements were identical // or there weren't enough distinct elements after firstSmallest. if (secondSmallest == INT_MAX) { printf("No second smallest element found (all elements might be same).\n"); } else { printf("The smallest element is: %d\n", firstSmallest); printf("The second smallest element is: %d\n", secondSmallest); } return 0; }
Output
Clear
ADVERTISEMENTS