// calculate histogram // input is read from stdin: non-negative integers, one number per line // CO904, Ellak Somfai #include #include #define MAX(x,y) ((x)<(y) ? (y) : (x)) int main() { int i; int x_max = -1; int *count; int count_size; // allocate small array, will be extended later if necessary count_size = 16; count = calloc(count_size, sizeof(int)); if (count == NULL) { perror(NULL); exit(1); } // main loop: reading numbers for (;;) { int x; int ret; // read a number ret = scanf("%d", &x); if (ret != 1) { // end of input: break out of loop break; } x_max = MAX(x, x_max); // extend array if too small if (x_max >= count_size) { int count_size_new; int tmp; count_size_new = 2*x_max; count = realloc(count, count_size_new * sizeof(int)); if (count == NULL) { perror(NULL); exit(1); } for (tmp = count_size; tmp < count_size_new; tmp++) { count[tmp] = 0; } count_size = count_size_new; } // increment counter count[x]++; } // print out counters for (i = 0; i <= x_max; i++) { printf("%d %d\n", i, count[i]); } return 0; }