In my code, in order to find the number of words by counting the number of spaces, I am having a logical error

My intention is to count the number of spaces using a for loop and an 'if' condition. I want the loop to keep going even when the condition given under 'if' is not satisfied, but it isn't working

This is my code:

 //counting no of words
int words=0;
int spaces=0;
for (int j=0,m=strlen(s);s[j]<m;j++)
    if(s[j]==' ')
words= (spaces + 1);
printf("%i words\n",words);

1 Answer 1


I don't know what you mean by "isn't working," but I do see a logic error in your loop declaration. s[j]<m means that your loop will run as long as the numerical value of the character at s[j] is less than the length of s, since m = strlen(s). What you want to do is run the loop until j is no longer less than m (j < m), meaning that your loop will iterate over all characters in the string.

Hope that helps. If not, let me know what the specific problem is, and I will try to help further.

  • Thank you ! Corrected that and it works now :) Feb 26, 2021 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .