I am supposed to write a program to print a histogram of the lengths of words in its input. When I compile my current code I get some random output... Any ideas how to solve this problem?
Ok guys… I tried to take into account your suggestions, so here is what I came up with so far:
#include <stdio.h>
int main()
{
int c, i, j, word, inspace, length;
length = 0;
word = 0;
inspace = 0;
int lengths [20];
for (i=0; i<20; ++i)
lengths[i] = 0; // initialize elements
i = 0;
while ((c = getchar()) != EOF ) {
if (c != ' ' && c != '\t' && c != '\n') {
++length;
inspace = 1;
if (length < 100)
{
++lengths[length];
}
}
if (c == ' ' || c == '\t' || c == '\n')
{
if (inspace == 1)
inspace = 0;
;
++word;
}
}
printf( "histogram:");
for (i=0; i<20; ++i) {
printf( "%2d", i);
for (j = 0; j < lengths[i]; ++j)
printf("*");
printf("\n");
}
}
Still I am getting this kind of output:
here we gohistogram: 0 1* 2* 3* 4* 5* 6* 7* 8* 9 10 11 12 13 14 15 16 17 18 19
Aucun commentaire:
Enregistrer un commentaire