1-13
Quest: page 24
- Write a program to print a histogram of the length of the words in its input. It is easy to draw the histogram with the bars horizontal. a vertical orientation is more challenging.
- step 1 generate testdata for the programnote
i generated a file with containing each word 3 times with a length from 1 to 99
generate testfile
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int main() {
FILE *f = fopen("txt", "w");
if (f == NULL) {
return EXIT_FAILURE;
}
for (int i = 1; i < MAX; i++) {
for (int k = 0; k < 3; k++) {
for (int j = 0; j < i; j++) {
fprintf(f, "w");
}
fprintf(f, " ");
}
fprintf(f, "\n");
}
fclose(f);
return EXIT_SUCCESS;
}
- step 2 print the histogramnote
My assumption is that each word is no longer than 1000 characters.
histogram program
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int main() {
int c;
int wl = 0;
int vi[MAX] = {0};
while ((c = getchar()) != EOF) {
// lets assume there are only three seperators
if (c == ' ' || c == '\t' || c == '\n') {
// note here we check if the current wl fits into the array
if (wl <= MAX && wl > 0) {
vi[wl]++;
}
wl = 0;
} else {
wl++;
}
}
for (int i = 0; i < MAX; i++) {
if (vi[i] > 0) {
printf("wordlength %d: %d times\n", i, vi[i]);
}
}
}