Write a C program to count the lines, words and characters in a given text.
Algorithm:
step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character
with newline char „\n‟ to count no of lines
Step
4: Compare
each character
with tab
char „\t\‟ or space
char „
„ to
count no
of words
Step
5: Compare
first character
with NULL
char „\0‟ to find
the end
of text
Step 6: No of characters = length of each line of text
Step 7: Print no of lines, no of
words, no of chars
Step 8: Stop
PROGRAM
#include <stdio.h>
int main()
{
char str[100];//input string with size 100
int words=0,newline=0,characters=0; // counter variables
printf("ENTER STRING AND PRESS ~ \n");
scanf("%[^~]",&str);//scanf formatting
for(int i=0;str[i]!='\0';i++)
{
if(str[i] == ' ')
{
words++;
}
else if(str[i] == '\n')
{
newline++;
words++;//since with every next line new words start.
}
else if(str[i] != ' ' && str[i] != '\n')
{
characters++;
}
}
if(characters > 0)
{
words++;
newline++;
}
printf("Total number of words : %d\n",words);
printf("Total number of lines : %d\n",newline);
printf("Total number of characters : %d\n",characters);
return 0;
}
OUTPUT:
ENTER STRING AND PRESS ~
hello
this is c
programm~
Total number of words : 5
Total number of lines : 3
Total number of characters : 20
What is counter here
ReplyDelete