The program finds the second largest element persistent in the given an array of integers.
For Example:
Sample Input: arr[] = {8, 1, 18, 9, 13, 5}
Sample Output: The second largest element is 13.
Explanation: The largest element of the array is 18 and the second largest element is 13
/* C Program to find Second largest Number in an Array */ #include <stdio.h> #include <limits.h> int main() { int arr[50], i, size, firstL, secondL; printf("Please Enter the Number of elements in an array : \n"); scanf("%d", &size); printf("Please Enter %d elements of an Array \n", size); for (i = 0; i < size; i++) { scanf("%d", &arr[i]); } firstL = secondL = INT_MIN; for (i = 0; i < size; i++) { if(arr[i] > firstL) { secondL = firstL; firstL = arr[i]; } else if(arr[i] > secondL && arr[i] < firstL) { secondL = arr[i]; } }
printf("\nThe Largest Number in this Array = %d", firstL); if (secondL == INT_MIN) { printf("The Second Largest Number does not exist.\n"); } else { printf("\nThe Second Largest Number in this Array = %d", secondL); } return 0; }
Test Case 1:
Please Enter the Number of elements in an array :
5
Please Enter 5 elements of an Array
10
14
25
4
8
The Largest Number in this Array = 25
The Second Largest Number in this Array = 14
Test Case 2:
Please Enter the Number of elements in an array :
3
Please Enter 3 elements of an Array
14
14
8
The Largest Number in this Array = 14
The Second Largest Number in this Array = 8
Test Case 3:
Please Enter the Number of elements in an array :
3
Please Enter 3 elements of an Array
5
3
3
The Largest Number in this Array = 5
The Second Largest Number in this Array = 3
Test Case 4:
Please Enter the Number of elements in an array :
4
Please Enter 4 elements of an Array
8
8
8
8
The Largest Number in this Array = 8
The Second Largest Number does not exist.