C program to count number of words in a string

Write a C program to count total number of words in a string using loop. How to find total number of words in a given string using loops in C programming.

Example:
Input string: I love C programming!
Total number of words: 4

Required knowledge

Basic C programming, If else, For loop, String

Logic to count number of words

To count total number of words in a string we just need to count total number of white spaces which includes single blank space(' '), Tab ('\t'), New line ('\n').

Algorithm to find total number of words in a string
%%Input : text {Array of characters /String}
        N {Size of the string}
Begin:
    words ← 0;
    For i ← 0 to N do
        If (text [i] == ' ', '\t', '\n') then
            wordword + 1;
        End if
    End for
End


Program to count number of words in string

/**
 * C program to count total number of words in a string
 */

#include <stdio.h>

#define MAX_SIZE 100 //Maximum size of the string

int main()
{
    char string[MAX_SIZE];
    int i, words;

    /* Reads a string from user */
    printf("Enter any string: ");
    gets(string);

    i = 0;
    words = 1;

    /* Runs a loop till end of string */
    while(string[i]!='\0')
    {
        /* If the current character(string[i]) is white space */
        if(string[i]==' ' || string[i]=='\n' || string[i]=='\t')
        {
            words++;
        }

        i++;
    }

    printf("Total number of words = %d\n", words);

    return 0;
} 


Output
Enter any string: I love C programming!
Total number of words = 4

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment