C program to find count of specific character

C program to find count of specific character

Question

Write a C program to find count of ‘a’ in String. The String must be generated from the given Substring.

 

 

We are given a Substring from which generate a  string by repeatedly joining/appending the given substring. In the  Example ‘abaabaabaa’ is the string generated from ‘abc’. The limit is 10. Count of ‘a’  is 7. In the next example count of a is 10.

Logic

  • Create a outer loop and run that for limit times.
  • Check the first index of sub-string whether it is ‘a’ or not. Increment count if yes.
  • Increment the index and again check. Repeat this until you reach the end of substring.
  • After that reset the index of Substring to j=0 and check again.

 

Program

#include<stdio.h>
int main()
{

    char arr[20];
    int i,j=0,l,count=0;
    gets(arr);                      //get Substring

    scanf("%d",&l);                 //Limit

    for(i=0;i<l;i++)                //Run until the given LIMIT
    {
        if(arr[j]!='\0')
        {
            if(arr[j]=='a')
               {
                 count++;           //increase count

               }
            j++;                    //increment index of substring
        }
        else{                       //Substring reached end
                
                j=0;                //reset index
                if(arr[j]=='a')
                {
                    count++;        //increase count
                }
                j++;
        }


    }

printf("\n%d",count);               //count of 'a'

}
</pre>

 

You might also like..

To remove characters in string without including alphabets.

Program to print mismatched characters

 

 

Sree Hari Sanjeev

The founder and CEO of Wisdom Overflow. His enthusiasm and effort has taken the blog to next level. You will be motivated just by taking a look at his daily schedule.