Array Exercises
Write a C program to find largest and second largest element in an array. How to find second largest element in array in C programming language. Logic to find second largest element in array in C program.
Required knowledge
Basic C programming, If else, c-Arrays, C Loops
Logic to find second largest element
Step by step descriptive logic to find second largest element in array.
- Input size and elements in array, store it in some variable say size and arr.
- 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.
- Iterate though all array elements, run a loop from 0 to size - 1. Loop structure should look like for(i=0; i<size; i++).
- 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].
- 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].
Program to find second largest element in array
/** * C program to find second largest number in an array */ #include <stdio.h> #include <limits.h> // For INT_MIN #define MAX_SIZE 1000 // Maximum array size int main() { int arr[MAX_SIZE], size, i; int max1, max2; /* Input size of the array */ printf("Enter size of the array (1-1000): "); scanf("%d", &size); /* Input array elements */ printf("Enter elements in the array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } max1 = max2 = INT_MIN; /* * Check for first largest and second */ for(i=0; i<size; i++) { if(arr[i] > 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[i]; } else if(arr[i] > max2 && arr[i] < max1) { /* * If current array element is less than first largest * but is greater than second largest then make it * second largest */ max2 = arr[i]; } } printf("First largest = %d\n", max1); printf("Second largest = %d", max2); return 0; }