C Program to Find Second largest Number in an Array

C Program to Find Second largest Number in an Array

C program to find second largest number in an array; Through this tutorial, we will learn how to find second largest number in an array in c program.

Algorithm to Find Second largest Number in an Array

Use the following 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 output 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

Recommended C Programs

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *