C Program to Find the Second Smallest Element in an Array

Write a C program to find the second smallest element in an array using for loop. In this c example, the if statement checks whether array items are smaller than the smallest variable and stores the second smallest array element.

#include <stdio.h>
#include <limits.h>
 
int main()
{
	int i, Size;
	int smallest, secSmallest;
	
	printf("\nEnter Second Smallest Number Array Size = ");
	scanf("%d", &Size);

	int arr[Size];
	
	printf("\nEnter %d elements of an Array = ", Size);
	for (i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
    }
	 
	smallest = secSmallest = INT_MAX;  
	   
	for (i = 0; i < Size; i++)
	{
		if(arr[i] < smallest)
		{
			secSmallest = smallest;
			smallest = arr[i];
		}
		else if(arr[i] < secSmallest && arr[i] != smallest)
		{
			secSmallest = arr[i];
		}	
	}
	printf("\nThe Smallest Number in this Array =  %d\n", smallest);
	printf("The second Small Number in this Array =  %d\n", secSmallest);
	
}
C Program to Find the Second Smallest Element in an Array

In this c program, we sorted the array in descending order so, the last but one element is the second smallest array element.

#include <stdio.h>
#include <limits.h>
 
int main()
{
	int Size, i;
	
	printf("\nEnter Second Smallest Number Array Size = ");
	scanf("%d", &Size);
	
	int arr[Size];

	printf("\nEnter %d elements of an Array = ", Size);
	for (i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
    }
	   
	for (i = 0; i < Size; i++)
	{
		int temp;
		for(int j = i + 1; j < Size; j++)
		{
			if(arr[i] < arr[j])
			{
				temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
	}
	printf("\nThe Smallest Number in this Array =  %d\n", arr[Size - 1]);
	printf("The second Small Number in this Array =  %d\n", arr[Size - 2]);
	
}
Enter Second Smallest Number Array Size = 8

Enter 8 elements of an Array = 11 99 14 22 7 90 3 20

The Smallest Number in this Array =  3
The second Small Number in this Array =  7