C bootcamp · Lab 22

Unique and sorted

mediumArrays12 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, remove duplicates, and print the remaining values sorted ascending on one line.

Sort first — then duplicates sit next to each other, so you can skip any value equal to the one before it.

Input. Integers separated by spaces.

Output. The distinct values, ascending, space-separated.

Examples

Example 1 — Duplicates removed, order ascending.
Input
3 1 2 3 1 5
Output
1 2 3 5
Example 2
Input
4 4 4
Output
4
Hint
  1. qsort the array ascending.
  2. Print arr[i] only when i == 0 or arr[i] != arr[i-1].
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);
  for (int i = 0; i < n; i++) {
    if (i == 0 || arr[i] != arr[i - 1]) printf("%d ", arr[i]);
  }
  printf("\n");
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.