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.
#include <stdio.h>
#include <string.h>
main()
{
int smallest, secondsmallest;
int array[100], size, i;
printf("\n How many elements do you want to enter: ");
scanf("%d", &size);
printf("\nEnter %d elements: ", size);
for (i = 0 ; i < size; i++)
scanf("%d", &array[i]);
if (array[0] < array[1]) {
smallest = array[0];
secondsmallest = array[1];
}
else {
smallest = array[1];
secondsmallest = array[0];
}
for (i = 2; i < size; i++) {
if (array[i] < smallest) {
secondsmallest = smallest;
smallest = array[i];
}
else if (array[i] < secondsmallest) {
secondsmallest = array[i];
}
}
printf(" \nSecond smallest element is %d", secondsmallest);
}
$ 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
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice Computer Science MCQs
- Check C Books
- Practice BCA MCQs
- Apply for Computer Science Internship
- Apply for C Internship