calloc and Counting
Completed
Read n and then n numbers between 0 and n−1. Use calloc (which zero-fills) for a counts array and print the numbers that never appeared, or all present.
Input
n, then n integers.
Output
One line.
Example
Input
6 0 1 1 4 5 5
Output
2 3
Editor
C
Hints
calloc(count, size) allocates and sets every byte to zero.
Solution explanation
malloc leaves garbage in the memory; calloc clears it.
Show solution
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, x, missing = 0;
scanf("%d", &n);
int *seen = calloc(n, sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &x);
seen[x] = 1;
}
for (int v = 0; v < n; v++) {
if (seen[v] == 0) {
if (missing) printf(" ");
printf("%d", v);
missing = 1;
}
}
printf(missing ? "\n" : "all present\n");
free(seen);
return 0;
}