facebook like button

27 April, 2011

program 33: program to count lines and words

The need:
     This program takes a whole paragraph as input and calculates total number of characters, words and lines.

The code: 
--------------------------------------------
//A program to count lines
#include<stdio.h>
#include<string.h>
main( )
{
    char line[500],ctr;
    int i,c,end=0,characters=0,words=0,lines=0;
    printf("key in text =>   ");
    while(end==0)
    {
        c=0;
        while((ctr=getchar())!='\n')
        line[c++]=ctr;
        line[c]='\0';
        if(line[0]=='\0')
        break;
        else
        {
            words++;
            for(i=0;line[i]!='\0';i++)
            if(line[i]==' '|| line[i]=='\t')
            words++;
        }
        lines=lines+1;
        characters=characters+strlen(line);
    }
    printf("\n");
    printf("no lines=> %d\n",lines);
    printf("no of words=> %d\n",words);
    printf("no of characters=> %d\n",characters);
}
--------------------------------------------
 
The approach:
First of all run the program. This program takes input until you press enter 2 times continuously thus allowing you to enter more than one line (recall that in previous programs whenever you gave characters as input to your program and pressed ENTER key it stopped taking more characters). After taking input the program gives the output.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply