C Online Compiler
Example: Find Second Largest Element (Sorting) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Second Largest Element (Sorting) #include <stdio.h> void sortArrayDescending(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] < arr[j+1]) { // Swap elements int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } int main() { int arr[] = {12, 35, 1, 10, 34, 1}; int n = sizeof(arr) / sizeof(arr[0]); if (n < 2) { printf("Array must have at least two elements.\n"); return 0; } // Step 1: Sort the array in descending order sortArrayDescending(arr, n); // Step 2: Find the second distinct largest element int largest = arr[0]; int secondLargest = -1; // Sentinel value indicating not found for (int i = 1; i < n; i++) { if (arr[i] < largest) { // Found an element smaller than the largest secondLargest = arr[i]; break; // This is our second largest } } if (secondLargest != -1) { printf("The second largest element is: %d\n", secondLargest); } else { printf("No second distinct largest element found.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS