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

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *