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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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