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:
- Start Program
- Take input size and elements in array and store it in some variables.
- Declare two variables
max1
andmax2
to store first and second largest elements. Store minimum integer value in both i.e.max1 = max2 = INT_MIN
. - Iterate for loop from 0 to
size
. - 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
andmax1 = arr[i]
. - Else if the current array element is greater than
max2
but less thanmax1
then make current array element as second largest i.e.max2 = arr[i]
. - Print result
- 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