15. write a C program to count the lines,words and characters in a given text


Program to count the lines,words and characters in a given text.

Source Code:

#include<stdio.h>
int main()
{
char str[200];
int line, word, ch;
 line = word = ch = 1;
printf("Enter string terminated with ~ :\n");
scanf("%[^~]", str);
   for(int i=0; str[i]!='\0'; i++)
   {
      if(str[i]=='\n')
      {
         line++;
         word++;
      }
      else
      {
         if(str[i]==' '||str[i]=='\t')
         {
            word++;
            ch++;
         }
         else {
            ch++;
         }
      }
   }
   printf("Character counts = %d\n", ch);
   printf("Word counts = %d\n", word);
   printf("Line counts = %d\n", line);
   return 0;
}

Output:

Enter string terminated with ~ :
Welcome to c~
Character counts =12
Word counts =3 
Line counts =1

No comments:

Post a Comment