Reputation: 169
So I'm new in C language and I'm trying to do a histogram with the length of the words the user typed, I have a solution but my second for loop always fail, I code like 5 for loop and every of them just stop after the second or third iteration, Am I missing something please help. Here's my code.
#include<stdio.h>
int main(){
int i,x,c,r,size;
int wa[10];
size=0;
for(i=0;i<10;i++){
wa[i]=0;
}
while((c=getchar())!=EOF){
switch(c){
case' ':{
wa[size]++;
size=0;
break;}
case'\n':{
wa[size]++;
size=0;
break;}
case'\t':{
wa[size]++;
size=0;
break;}
default:{
size++;
break;
}
}
}
for(r=0;r<=10;++r){
printf("%d",r);
for(x=0;x<wa[r];x++){
printf("*");
}
printf("\n");
}
return 0;
}
Upvotes: 2
Views: 192
Reputation: 662
first, for testing purposes when running from Linux commandline Ctrl+d emulates EOF
second, your for loop iterates between ( 0 -10 inclusive ), your wa
array index however is ranging from (0 - 9 inclusive ) which means:
for(x=0;x
call may cause SEGFAULT
abcdEOF
fourth, following the second paragraph when entering valus to the array your indexing is wrong
as far as the assumption that the longest words is 10char long thats fine but you must verify that the size
never exceeds the value of 9 or if you will correct the wa
update then 10 exceeding this value will cause segfault due to updating un-allocated index in the array
Hope this helps
Upvotes: 1
Reputation: 1801
The first for loop will start from 1, and in the second for loop replace wa[4] with wa[r].
Your code also assume that no word will be longer than 10 char.
Upvotes: 0