Jared Josafhat H Z
Jared Josafhat H Z

Reputation: 169

C for loop failing

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

Answers (2)

Omer Dagan
Omer Dagan

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

    • third, you are missing a simple case where the input is just one word with no whitespace after, something like

    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

Md Monjur Ul Hasan
Md Monjur Ul Hasan

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

Related Questions