C program to find second smallest number in an array; Through this tutorial, we will learn how to find second smallest number in an array in c program.
Algorithm to Find Second Smallest Number in an Array
Use the following algorithm to write a program to find second smallest number in an array; as follows:
- Start Program
- Declare an array and some variables.
- Take input the array elements from user.
- Find the smallest element (first_smallest) in the array in the first traversal.
- Find the smallest element (second_smallest) by skipping the first_smallest element.
- Display second_smallest.
- End Program.
C Program to Find Second Smallest Number in an Array
#include <stdio.h> #include <limits.h> int main() { int arr[50], n, i; //Enter the size of an array printf("Enter the size of an array (Max 50) \n"); scanf("%d", &n); printf("Enter an array elements\n"); //Input array values for(i = 0; i < n; i++) { scanf("%d", &arr[i]); } //Intialize variable with max int value int smallest = INT_MAX; int secondSmallest = INT_MAX; //Traverse an array for(i = 0; i < n; i++) { //If element is smaller if(arr[i] < smallest) { secondSmallest = smallest; smallest = arr[i]; } if(arr[i] > smallest && arr[i] < secondSmallest) { secondSmallest = arr[i]; } } printf("Second smallest %d", secondSmallest); return 0; }
The output of the above c program; is as follows:
Enter the size of an array (Max 50) 5 Enter an array elements 1 2 4 5 45 Second smallest 2