C Program to Find Second Smallest of n Elements with Complexity Constraint

This C program finds second smallest of n Elements in an array.

Given an array of n Integers, this algorithm finds the second smallest element out of it.

Here is the source code of the C program to find the second smallest number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. main()
  5. {
  6.     int smallest, secondsmallest;
  7.     int array[100], size, i;
  8.     printf("\n How many elements do you want to enter: ");
  9.     scanf("%d", &size);
  10.     printf("\nEnter %d elements: ", size);
  11.     for (i = 0 ; i < size; i++)
  12.         scanf("%d", &array[i]);
  13.     if (array[0] < array[1]) {
  14.         smallest = array[0];
  15.         secondsmallest = array[1];
  16.     }
  17.     else {
  18.       smallest = array[1];
  19.       secondsmallest = array[0];
  20.     }
  21.     for (i = 2; i < size; i++) {
  22.         if (array[i] < smallest) {
  23.         secondsmallest = smallest;
  24.         smallest = array[i];
  25.         }
  26.         else if (array[i] < secondsmallest) {
  27.             secondsmallest = array[i];
  28.         }
  29.     }
  30.     printf(" \nSecond smallest element is %d", secondsmallest);
  31. }

$ gcc secondsmallest.c -o secondsmallest
$ ./secondsmallest
 
How many numbers you want to enter: 10
 
Enter 10 numbers :  31 20 35 333 758 45 62 89 106 94
 
Second smallest element is 31

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.