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.

IntermediateArraysLoopsIndexing

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

second-largest-array-element.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Second largest = 7
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Maintain the largest and second-largest distinct values in a single pass.
  3. 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.