Description:
In this program we have to count
the no of lines, no of words and no of characters in a given program or given
text by using the string function
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>
main()
{
char
line[81], ctr;
int i,c,
end
= 0,
characters
= 0,
words
= 0,
lines
= 0;
printf("KEY
IN THE TEXT.\n");
printf("GIVE
ONE SPACE AFTER EACH WORD.\n");
printf("WHEN
COMPLETED, PRESS 'RETURN'.\n\n");
while( end
== 0)
{
/*
Reading a line of text */
c
= 0;
while((ctr=getchar())
!= '\n')
line[c++]
= ctr;
line[c]
= '\0';
/*
counting the words in a line */
if(line[0]
== '\0')
break
;
else
{
words++;
for(i=0;
line[i] != '\0';i++)
if(line[i]
== ' ' || line[i] == '\t')
words++;
}
/*
counting lines and characters */
lines
= lines +1;
characters
= characters + strlen(line);
}
printf
("\n");
printf("Number
of lines = %d\n", lines);
printf("Number
of words = %d\n", words);
printf("Number
of characters = %d\n", characters);
}
Output
1.KEY IN THE TEXT.
GIVE ONE SPACE
AFTER EACH WORD.
WHEN COMPLETED,
PRESS 'RETURN'.
Admiration is a
very short-lived passion.
Admiration involves
a glorious obliquity of vision.
Always we like
those who admire us but we do not
like those whom
we admire.
Fools admire, but
men of sense approve.
Number of lines =
5
Number of words =
36
Number of characters
= 205
Conclusion:
The program is error free
VIVA QUESATIONS:
1) What
is use of strlen() ?
Ans: to read a string length
2) what
is the use of getc() function ?
Ans: To read the character one by
one.
3) What
is the use of strstr () ?
Ans: The function
strstr() searches one string for the occurrence of another.It accepts
two
strings as parameters and searches the first string for an occurrence of
the
second
No comments:
Post a Comment