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>
#include <conio.h>
#include <string.h>
void main()
{
   char str[100];
   int i = 0, l = 0, f = 1;
   clrscr();
   puts("Enter any string\n");
   gets(str);
   for(i = 0; str[i] !='\0'; i++)
   {
      l = l + 1;
   }
   printf("The number of characters in the string are %d\n", l);
   for(i = 0; i <= l-1; i++)
   {
      if(str[i] == ' ')
      {
    f = f + 1;
      }
   }
   printf("The number of words in the string are %d", f);
   getch();
}

Input & Output:

Enter any string
abc def ghi jkl mno pqr stu vwx yz
The number of characters in the string are 34
The number of words in the string are 9