Index « Previous Next »

Question

Write a program that prompts the user to input a string, your program should count and display number of words in that string.

Source Code

#include <stdio.h>

int main()
{
    char str[80];
    int i, words = 0;

    printf("Enter a string: ");
    gets(str);

    for (i = 0; str[i] != '\0'; i++)
    {
        /* Checking for spaces */
        if (str[i] == ' ')
        {
            words++;
        }
    }

    printf("The number of words = %d", words + 1);

    return 0;
}

Output

Enter a string: The great aim of education is not knowledge but action.
The number of words = 10