Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q3) Write a program that counts the number of times a specific character occurs

ID: 3725450 • Letter: Q

Question

Q3) Write a program that counts the number of times a specific character occurs in a string. For example, if the string is "hello world" and the character being counted is '1', the prgram should output 3. The output should follow the format below (there are NO double spaces). Enter the length of the string: 13 Enter the string: hello world Enter search character: Characters found: 3 Modify the code from the previous problem by changing the datatype of the array to char instead of int. The line with malloc must also be change to match the datatype. Do not sort the array. It may be beneficial to run sed '3d;9d;21,30d' sort.c> count-char.c to begin structuring your program. Another idea may be to copy the old code and modify the necessary lines, this is done by cp avg-var.c count_char.c. Note: Even though “hello world" only has 11 letters (including the space), there is an addi- tional line feed character before and after the letters. Thus, the total size of the string is the number of letters + 2. Name your file count_char.c.

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
int main()
{
   printf("Enter the length of the string:");
   int n,i=0;
   scanf("%d",&n);//reading input
   //you can modify this line
   //int *a = (int *)malloc(sizeof(int)*n+2);
   char *a = (char *)malloc(sizeof(char)*n);//declaration
   //dynamic allcoation
  
   printf("Enter the string:");
   while(i<n)//reading string...
   {
       scanf("%c",(a+i));
       i++;
   }
   char c;
   printf("Enter search character:");
   scanf("%c",&c);
   i=0;
   int count=0;
   //finding character cound
   while(i<n)
   {
       if(*(a+i)==c)count++;
           i++;
   }
   printf("Characters found: %d ",count);
  
  
   return 0;  
}

output:

Enter the length of the string:13
Enter the string:hello world
Enter search character:l
Characters found: 3


Process exited normally.
Press any key to continue . . .