• Register
100 points
5 1

This is very simple question to code.Here,we will count the occurrence of character entered by user in a given string.We will iterate all over the string and match the character to each element of string.

Algorithm

  • Read the string from gets and take count variable and initialize to zero.
  • Compare the entered character to each elements of the given string using for loop.
  • If entered character matches with the elements of string then increment the count variable by 1.
  • Print the count of that entered character.

Code

#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[1000],temp;  
    int i,count=0,leng;
 
    printf("Enter  the string : ");
    gets(str);
    printf("Enter character: ");
    temp=getchar();
    leng=strlen(str);
    
    for(i=0;i<leng;i++)  
    {
    	if(s[i]==temp)
    	{
          count++;
		}
 	}
     
	printf("character '%c' occurs %d times in a given string\n ",temp,count);
 
 	 
     
    return 0;
}

Output

Enter the string:acfeertehue
Enter character : e
character 'e' occurs 4 times in a given string