C Program to find Second smallest element in the array

Description

Get array size n and n elements of array, then find the second smallest element among those elements.
Input:
5
5 7 9 3 1
Output:
3

Solution

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int main()
{
	int *a,n,i,min,second_min;
	printf("Enter size of array:");
	scanf("%d",&n);

	a=malloc(sizeof(int)*n);
	printf("Enter %d Elements:",n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	
	min=INT_MAX;
	second_min=INT_MAX;
	for(i=0;i<n;i++)
	{
		if(a[i]<min)
		{
			second_min=min;
			min=a[i];
		}
		else if(a[i] < second_min && a[i]!=min)
		{
			second_min=a[i];
		}
	}

	printf("The second minimum is : %d",second_min);
	return 0;
}

Explanation

Initialize min and second_min with INT_MAX(INT_MAX is constant holds maximum integer value)

 visit every location in the array
   a) If the current element in array  a[i] is less than min. Then update min and second_min as,
      second_min = min
      min = a[i]
   b) If the current element is greater than min and less than second_min,
      then update second_min to store the value of current variable as
      second_min = arr[i]
print the value stored in second_min.




Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution