C Online Compiler
Example: Find Second Largest Element (Single-Pass Scan) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Find Second Largest Element (Single-Pass Scan) #include <stdio.h> #include <limits.h> // For INT_MIN 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; } // Initialize largest and secondLargest // Ensure largest is initially greater or equal to secondLargest (or they are distinct sentinels) int largest = INT_MIN, secondLargest = INT_MIN; // Handle initial two elements if possible to set a baseline // Or initialize with first relevant values, careful with duplicates // Robust initialization: iterate from start and update for (int i = 0; i < n; i++) { if (arr[i] > largest) { secondLargest = largest; // The old largest becomes the new second largest largest = arr[i]; // Update largest } else if (arr[i] > secondLargest && arr[i] < largest) { secondLargest = arr[i]; // Update second largest only if it's distinct and smaller than largest } } if (secondLargest == INT_MIN) { printf("No second distinct largest element found.\n"); } else { printf("The second largest element is: %d\n", secondLargest); } return 0; }
Output
Clear
ADVERTISEMENTS