C bootcamp · Lab 21

Second largest

mediumArrays15 minLesson: Arrays

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a line of integers and print the second largest distinct value.

If the biggest number appears twice, the second largest is still the next different number down. Sort first, then scan.

Input. Integers separated by spaces (at least two distinct values).

Output. One integer: the second largest distinct value.

Examples

Example 1 — Two 7s collapse to one, so second largest is 4.
Input
4 1 7 7 3
Output
4
Example 2
Input
10 20 30
Output
20
Hint
  1. Read until scanf fails: while (scanf("%d", &x) == 1) arr[n++] = x;
  2. qsort ascending, then walk down from the top skipping values equal to the largest.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>
#include <stdlib.h>

int cmp(const void *a, const void *b) {
  int x = *(const int *)a, y = *(const int *)b;
  return (x > y) - (x < y);
}

int main(void) {
  int arr[100000], n = 0, x;
  while (scanf("%d", &x) == 1) arr[n++] = x;
  qsort(arr, n, sizeof(int), cmp);
  int largest = arr[n - 1];
  for (int i = n - 2; i >= 0; i--) {
    if (arr[i] != largest) { printf("%d\n", arr[i]); return 0; }
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.