C program to count a letter repeated in a sentence.

CServer Side ProgrammingProgramming

Problem

Write a program to count a letter, which is entered by the user at console. How many times that letter is repeated in a sentence need to be printed on screen by using strlen() function.

Solution

The logics we used to count a letter are as follows −

  • Asking the user to enter a sentence at runtime.
printf("Enter a sentence\n");
gets(str);
  • Asking the user to enter a letter at runtime.
printf("Enter a character to check how many times it is repeating\n");
scanf("%c",&c);
  • The logic to count the letter in a sentence is as follows −
for(i=0;i<strlen(str);i++){
   if(str[i]==c){
      count++;
   }
}
  • Finally print the count

Example

Following is the C program to count a letter that is repeated for number of times in a sentence −

 Live Demo

#include<stdio.h>
#include<string.h>
main(){
   int i,count=0;
   char c,str[100];
   printf("Enter a sentence\n");
   gets(str);
   printf("Enter a character to check how many times it is repeating\n");
   scanf("%c",&c);
   for(i=0;i<strlen(str);i++){
      if(str[i]==c){
         count++;
      }
   }
   printf("Letter %c repeated %d times\n",c,count);
}

Output

When the above program is executed, it produces the following output −

Enter a sentence
Here are the C Programming question and answers
Enter a character to check how many times it is repeating
n
Letter n repeated 4 times
raja
Updated on 25-Mar-2021 07:24:11

Advertisements