C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING
Find the Second-Largest Distinct Array Element
Learn how to find the second-largest distinct array element using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
6 9 4 9 7 2 7
Sample output
Second largest = 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int size, values[100], largest = 0, second = 0;
int hasLargest = 0, hasSecond = 0;
printf("Enter array size: ");
scanf("%d", &size);
if (size < 2 || size > 100) return 1;
for (int index = 0; index < size; index++) scanf("%d", &values[index]);
for (int index = 0; index < size; index++) {
int value = values[index];
if (!hasLargest || value > largest) {
if (hasLargest) { second = largest; hasSecond = 1; }
largest = value; hasLargest = 1;
} else if (value != largest && (!hasSecond || value > second)) {
second = value; hasSecond = 1;
}
}
if (hasSecond) printf("Second largest = %d\n", second);
else printf("No second distinct value.\n");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Second largest = 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Maintain the largest and second-largest distinct values in a single pass.
- Display the computed result.
Maintain the largest and second-largest distinct values in a single pass.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
