C Program to Count Occurrence of Character in String

C Program to Count Occurrence of Character in String:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().



#include<stdio.h>
main()
{
   char str[30];
   char a;
   int cnt=0,i;

   printf("Enter a string : ");
   scanf("%s",&str);

  printf("Enter the character to be search : ");
  a = getche();

   for(i=0;str[i]!='\0';i++)
    {
      if(str[i] == a)
         cnt++;
   }

   if (cnt == 0)
      printf("\nCharacter is not present in string");
   else
      printf("\nOccurence of character %c is: %d",a,cnt);
}

OUTPUT:

Enter a string : Barontuts
Enter the character to be search : t
Occurence of character t is: 2

Leave a Reply

Your email address will not be published. Required fields are marked *

four − 2 =