- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C program to count a letter repeated in a sentence.
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
"); gets(str);
- Asking the user to enter a letter at runtime.
printf("Enter a character to check how many times it is repeating
"); 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 −
#include<stdio.h> #include<string.h> main(){ int i,count=0; char c,str[100]; printf("Enter a sentence
"); gets(str); printf("Enter a character to check how many times it is repeating
"); scanf("%c",&c); for(i=0;i<strlen(str);i++){ if(str[i]==c){ count++; } } printf("Letter %c repeated %d times
",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
Advertisements