So I’m making a program which is supposed to print a horizontal histogram of the lengths of words in its input. So I changed the while into if so it now accepts more than 1 input. But what’s wrong with it this time? It won’t print the graph.
/*Write a program to print a histogram of the lengths of words in its input.
It is easy to draw the histogram with the bars horizontal*/
#include <stdio.h>
#define MAX 30
#define IN 1
#define OUT 0
int main()
{
int a,c,i,k,state,word[MAX];
a=0;
k=0;
state=OUT;
for(i=0;i<MAX;i++)
word[i]=0;
while((c=getchar())!=EOF)
{
if(c==' '||c=='\t'||c=='\n')
state=OUT;
else
state=IN;
if(state==IN)
a++;
if(state==OUT)
{
word[i]=a;
i++;
a=0;
}
}
/*This part is pissing me off, I don't know how to print X multiple times!*/
for(i=0;i<MAX;i++)
if(word[i]>0)
{
for(k=0;k<=word[i];k++)
putchar('-');
putchar('\n');
}
}
That’s your problem right there
This is basically an endless loop, it will loop forever incrementing
aEdit: Ok, part two then.
First off what you are doing with
ais not what you think you are doing.I think you think you are using it to count word length but you are not resetting it to
0after each word so it will in fact keep on counting number of found chars. Your histogram will just show growing numbers.Second, in your print loop you are using
iin both loops leading to a delicious mess of some sort.Edit: Part three
I just spotted that you are printing the histogram inside the input-loop on the conditional
This is probably not going to work, I suggest to move the printing outside the while loop and remove the condition
then it will get executed after you are finished taking input
Edit: Part four
You have reused
ias index into the array without setting it to zero, the consequence being that the program assigns word lengths to indexes 30-59 which are all outside the array, that it does not crash is just pure luck. Settingi = 0before entering the input loop makes the program work.Now all you have left to think about is why it prints word lengths one too long, I leave that as an exercise to the reader. Hint: It has to do with comparison operators