C Program to Find Second largest Number in an Array

In this tutorial, i am going to guide you how to find second largest number in an array in c program.

Algorithm to Find Second largest Number in an Array

Follow the below given algorithm to write a program to find second largest number in an array; as follows:

  1. Start Program
  2. Take input size and elements in array and store it in some variables.
  3. Declare two variables max1 and max2 to store first and second largest elements. Store minimum integer value in both i.e. max1 = max2 = INT_MIN.
  4. Iterate for loop from 0 to size.
  5. Inside loop, check if current array element is greater than max1, then make largest element as second largest and current array element as largest. Say, max2 = max1 and max1 = arr[i].
  6. Else if the current array element is greater than max2 but less than max1 then make current array element as second largest i.e. max2 = arr[i].
  7. Print result
  8. End Program.

C Program to Find Second largest Number in an Array

/* C Program to find Second largest Number in an Array */
#include <stdio.h>
#include <limits.h>
 
int main()
{
	int arr[50], i, Size;
	int first, second;
	
	printf("\n Please Enter the Number of elements in an array  :  ");
	scanf("%d", &Size);
	
	printf("\n Please Enter %d elements of an Array \n", Size);
	for (i = 0; i < Size; i++)
	{
		scanf("%d", &arr[i]);
    }
	 
	first = second = INT_MIN;  
	   
	for (i = 0; i < Size; i++)
	{
		if(arr[i] > first)
		{
			second = first;
			first = arr[i];
		}
		else if(arr[i] > second && arr[i] < first)
		{
			second = arr[i];
		}	
	}
	printf("\n The Largest Number in this Array =  %d", first);
	printf("\n The Second Largest Number in this Array =  %d", second);
	
	return 0;
}

The result of the above c program; is as follows:

Please Enter the Number of elements in an array  :  5
Please Enter 5 elements of an Array 
1 25 24 64 74
The Largest Number in this Array =  74
 The Second Largest Number in this Array =  64

More C Programming Tutorials

Leave a Comment