[Solved] How to count word length (K&R book exercise)


Try this code :

#include <stdio.h>

int main(void){
int array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int counter=0, c, position;
while ((c = getchar()) != EOF){
    if(c == ' ' || c == '\n' || c == '\t'){
        array[counter]++;
        counter = 0;
    } else {
        if(counter<9) {
            counter ++;
        }
    }
}
if(counter!=0) {
    array[counter]++;
}
for (position = 0; position < 10; ++position){
    printf("%d ", array[position]);
}
    return 0;
}

The problem with your code was that whenever a character was appearing, you were incrementing an array position. What is needed is to wait till the word is finished and as soon as we encounter ” “, we increment the word length position in the array.

solved How to count word length (K&R book exercise)