Skip to content
Home » C program to count number of words in a sentence

C program to count number of words in a sentence

Below is the program to count number of words in a sentence

#include <stdio.h>
int main(){
    char str[1000];
    int i,j;
    printf("Enter the string: ");
    fgets(str,1000,stdin);
    for(i=0;str[i]!='\0';i++){
        if(str[i]==' ' && str[i+1]!=' '){
            j++;
        }
    }
    printf("Total number of words in the given sentence is: %d",j+1);
}

Output:

Enter the string: I love Programming
Total number of words in the given sentence is: 3