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. ## 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 id a<a and min2 as a, otherwise min1 = a and min2=a.
• 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 < a) {      min1 = a;      min2 = a;    }    else {      min2 = a;      min1 = a;    }        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 :57 8 1 9 2Output :2`