Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to find second smallest element of an array.

C Code Example — Array Programs

ADVERTISEMENT

C Program to find second smallest element of an array.

Objective

Write a C program to find the second smallest element of an array.

Algorithm / Approach

  1. Read an array of size n.
  2. Find the absolute smallest element (min) and save its exact index position in j.
  3. Initialize the second smallest smin to a different element (e.g., the last element).
  4. Loop through the array again to find the minimum value, BUT ignore the element at index j (if smin > a[i] && j != i).
  5. Print smin.
main.c
#include<stdio.h>
int main() {
 int a[50],n,i,j=0,min,smin;
 printf("Enter Array Size: ");
 scanf("%d",&n);
 printf("Enter %d element: ",n);
 for(i=0;i< n;i++)
  scanf("%d",&a[i]);
 min=a[0];
 for(i=1;i< n;i++){
  if(min > a[i]) {
   min = a[i];
   j = i;
  }
 }
 smin=a[n-j-1];
  for(i=1;i< n;i++){
   if(smin > a[i] && j != i)
    smin =a[i];
  }
 printf("2nd smallest:%d",smin);
 return 0;
}

Expected Output

Enter Array Size: 5
Enter 5 element: 1 2 3 4 5
2nd smallest:2

Explanation of the Program

  • To find the second smallest, we must first identify the absolute smallest and "remove" it from consideration.
  • Instead of physically deleting the smallest element (which is expensive in an array), we just record its index (j). When we do our second pass to find the smallest number, we explicitly tell the if statement to ignore index j.

Complexity

Time Complexity O(n) - Two separate passes through the array.
Space Complexity O(n)
ADVERTISEMENT