C Program to Find Second Smallest Number in an Array

In this tutorial, i am going to show you how to find second smallest number in an array in c program.

Algorithm to Find Second Smallest Number in an Array

Follow the below given algorithm to write a program to find second smallest number in an array; as follows:

  1. Start Program
  2. Declare an array and some variables.
  3. Take input the array elements from user.
  4. Find the smallest element (first_smallest) in the array in the first traversal.
  5. Find the smallest element (second_smallest) by skipping the first_smallest element.
  6. Display second_smallest.
  7. 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 result 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

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.