Contact Learn C
Copy Program Share Program

Program 82:To count number of times a letter repeated in sentence

Program 82:
#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 know it's repetance in sentence\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);
}
Explanation:

  1. This program starts with initializing :
    • str[100] → To store string with length of 100 which means it can store 100 letters
    • i →Used as helping variable
    • count→ To store number of  times a letter is repeated in a given string and is initilized to 0.
    • c →Used to store required letter
  2. printf("Enter a sentence\n");
    gets(str);
    Takes string from user.
  3. printf("Enter a character to know it's repetance in sentence\n");
    scanf("%c",&c);
    Takes a letter from user for which we want to know number of times it repeated
  4. for(i=0;i<strlen(str);i++)
    {
        if(str[i]==c)
        {
            count++;
        }
    }
    Same as previous programs the forloop traverse from 0 to length of string and compares each character from the string(say "hello world" from blow output)  with the given letter and the count is incremented by 1 each time it matches with the given letter(say 'l' from the below output).

 Output:

To count number of times a letter repeated in sentence

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide