C Programming Code Examples C > Arrays and Matrices Code Examples C program to find second largest number in an array C program to find second largest number in an array Write a C program to find the largest and second largest element in an array. How to find second largest element of an array in C programming language. Below is the step by step descriptive logic to find second largest element in an array. Input elements in an array, in some variable say array. Declare two variables to store first and second maximum values. Assume that the zeroth array element is the first as well as second largest element. Say max1 = array[0] and max2 = array[0]. Run a loop from 0 to N-1, the loop structure should look like for(j=0; j<N; j++). Inside the loop, check if current array element is greater than max1, then make the largest element as second largest and current array element as largest element. Say, max2 = max1 and max1 = array[j]. Else if the current array element is greater than max2 but is less than max1 then make current array element as second largest element i.e. max2 = array[j]. Algorithm to find second largest element in array %%Input : arr {Array in which largest is to be found} N {Size of the array} Begin: max1 = arr[0]; max2 = arr[0]; For j = 1 to N do If (arr[j] > max1) then max2 = max1; max1 = arr[j]; End if Else if (arr[j] > max2 && arr[j] < max1) then max2 = arr[j]; End if End for End #include <stdio.h> #include <limits.h> //For INT_MIN #define maxsize 1000 int main() { int arr[maxsize], N, j; int max1, max2; /* Input size of the array */ printf("Enter size of the array (1-1000): "); scanf("%d", &N); /* Input array elements */ printf("Enter elements in the array: "); for(j=0; j<N; j++) { scanf("%d", &arr[j]); } max1 = max2 = INT_MIN; /* * Check for first largest and second largest till N */ for(j=0; j<N; j++) { if(arr[j] > max1) { /* * If current element of the array is first largest * then make current max as second max * and then max as current array element */ max2 = max1; max1 = arr[j]; } else if(arr[j] > max2 && arr[j] < max1) { /* * If current array element is less than first largest * but is greater than second largest then make it * second largest */ max2 = arr[j]; } } printf("First largest = %d\n", max1); printf("Second largest = %d", max2); return 0; }