C Program to Find Second Smallest Number in an Array

C Program to Find Second Smallest Number in an Array

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:

  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 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

Recommended C Programs

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published.