This C program counts number of characters, number of words and number of lines in a given text.
Variables: nw-new word, nc-new character, nl-new line
ch-to store character.
getchar(): scans one character from keyboard and stores it in variable 'ch'.
Then it compares with character '#'.It will scan till the condition become false.
While loop: Inside the while loop,
1) If the scanned character is space, then new word and new character are incremented by 1.
2) If the scanned character is new line( means 'enter' is pressed), then new line and new word are increased by 1.
3) If the scanned character is character then new character is increased by 1.
Finally print nl, nw, nc.
Program Description
Variables: nw-new word, nc-new character, nl-new line
ch-to store character.
getchar(): scans one character from keyboard and stores it in variable 'ch'.
Then it compares with character '#'.It will scan till the condition become false.
While loop: Inside the while loop,
1) If the scanned character is space, then new word and new character are incremented by 1.
2) If the scanned character is new line( means 'enter' is pressed), then new line and new word are increased by 1.
3) If the scanned character is character then new character is increased by 1.
Finally print nl, nw, nc.
Source Code
/* program that counts number of lines, words and characters
Note: Don't forget to put '#' at the end of your text */
#include<stdio.h>
#include<conio.h>
void main()
{
int nw,nc,nl;
char ch;
clrscr();
nl=1;//new line
nw=0;//new word
nc=0;//new character
printf("\n Enter any text:\n");
while((ch=getchar())!='#')
{
if(ch==' ')
{
nw=nw+1;
nc=nc+1;
}
else if(ch=='\n')
{
nl=nl+1;
nw=nw+1;
}
else
{
nc=nc+1;
}
}
printf("\n Number of lines: %d",nl);
printf("\n Number of characters: %d",nc);
printf("\n Number of words: %d",nw);
getch();
}
Note: Don't forget to put '#' at the end of your text */
#include<stdio.h>
Output
Post a Comment