C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Find the Kth-Largest Array Element

Learn how to find the kth-largest array element using a clear C program.

IntermediateArraysSortingRank

PROBLEM UNDERSTANDING

Input and expected output

Sample input
6
7 10 4 3 20 15
3
Sample output
3th largest = 10

COMPLETE C PROGRAM

Complete C implementation

kth-largest-array-element.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int size, values[100], rank;

    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    for (int index = 0; index < size; index++) scanf("%d", &values[index]);
    scanf("%d", &rank);
    if (rank < 1 || rank > size) return 1;
    for (int start = 0; start < size - 1; start++) {
        int maximum = start;
        for (int index = start + 1; index < size; index++)
            if (values[index] > values[maximum]) maximum = index;
        int temporary = values[start]; values[start] = values[maximum]; values[maximum] = temporary;
    }
    printf("%dth largest = %d\n", rank, values[rank - 1]);
    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

3th largest = 10
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Sort in descending order and select the element at index K−1.
  3. Display the computed result.

Sort in descending order and select the element at index K−1.

EFFICIENCY

Time and space complexity

Time complexity

O(n²)

Auxiliary space

O(1)

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.