so, im learning a bit of c, and going through the k and r book, i got to this question and im stuck
its the one about write a program to print a histogram of the word lengths in its input (horizontal of course)
thing is, i did get it to work, but then i decided to make it check the text first, to get the largest word, then declare the array to the correct size, before executing the part about counting the words and the printf stuff
before i added the while statement to get the largest word stuff, it DID work !!!! now it doesnt
can anyone see why ? i been staring at it since yesterday
Code:
#include <stdio.h>
int main () {
int wordsize = 0;
int wordsizecheck = 0;
int largestword = 0;
int pl = 0;
int c, i = 0;
while ((c = getchar()) != EOF) { /*to find the largest word in the input, seems to work */
if (c == ' ' || c == '\t' || c == '\n') {
if (wordsizecheck > largestword) {
largestword = wordsizecheck;
}
wordsizecheck = 0;
}
else {
++wordsizecheck;
if (wordsizecheck > largestword) {
largestword = wordsizecheck;
}
}
}
printf("largest word = %d\n", largestword); /* to check it worked */
int wordlengths[largestword]; /*set the array*/
for (i = 0; i < largestword; ++i) {
wordlengths[i] = 0;
}
while ((c = getchar()) != EOF) {
/*count the words of a certain length (this worked before i added the stuff above*/
if (c == ' ' || c == '\t' || c == '\n') {
++wordlengths[wordsize - 1];
wordsize = 0;
}
else {
++wordsize;
}
}
if ((c = getchar()) == EOF) {
++wordlengths[wordsize - 1];
}
for (i = 0; i < largestword; ++i) { /*to check array, seems to indicate problam*/
printf("array value %d = %d\n", i, wordlengths[i]);
}
for (i = 0; i < largestword; ++i) { /* print histogram ( worked before :( */
printf("%4d | ", i + 1);
for (pl = 0; (pl <= wordlengths[i]) && (wordlengths[i] != 0) ; ++pl) {
printf("*");
}
printf("\n");
}
return 0;
}
any help id really appreciate, or any criticisms also, thanks