Saturday, October 5, 2013

Word Count

You have to write a program to count the number of words in the input. The program should read in the input text till end_of_file (EOF) and output the number of words found. A word can be taken to be a sequence of alphanumeric characters terminated by a space or by a newline.

Assume that there will not be any characters other than alphanumeric (a-z, A-Z, 0-9) and white spaces (blank, tabs and newlines) in the input.

Sample Input and Output:

Input:
This is a sample line of text
This is another line of text
This line is the 3rd line
This junk line contains 989902 99dsaWjJ8
This is the fifth and the last line of input

Output:36
015

Input:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
Output:
1

Solution:

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int j,flag=1;  
    char c;

        j=0;   
        while((c=getchar())!=EOF)
        {
                if(c=='    ' || c == '\n' || c == '\t')
                flag = 1;
                else if(flag==1)
                {
                        flag=0;
                        j++;
                }
        }

        printf("%d\n",j);
}

No comments:

Post a Comment