Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

C Program to find the second smallest element in an array

Finding second smallest element in an array

An array is a group of similar type of data that are addressed by an common name (Arr[]). Array of any type can be created and may have one or more dimensions, i.e. 1-D Array, 2-D Array etc. Here we will learn how to code a C program for finding second smallest element in an array.

second smallest element in C

Algorithm :

  • Take the size of the array from the user and store it in variable say n.
  • Declare an array of n size and take n input elements for the array from the user.
  • Now , Declare two variable say min1 and  min2.
  • Initialize them min1 as a[0] id a[0]<a[1] and min2 as a[1], otherwise min1 = a[1] and min2=a[0].
  • Iterate from i=2 to i=n-1 and check if the min1 >a[i] then update min2=min1 and min1 = a[i].
  • Else If min2 > a[i], then update min2 as min2 = a[i].

Code in C Based on above Algorithm

#include <stdio.h>

int main(){

int min1, min2, n;

scanf("%d", &n);

int a[n];

for (i = 0 ; i < n; i++)
scanf("%d", &a[i]);

if (a[0] < a[1]) {
min1 = a[0];
min2 = a[1];
}

else {
min2 = a[0];
min1 = a[1];
}

for (i = 2; i < n; i++) {

if (a[i] < min1) {
min2 = min1;
min1 = a[i];
}

else if (a[i] < min2) {
min2 = a[i];
}

}

printf("%d", min2);

}
Input :

5

7 8 1 9 2

Output :

2