Below is a C program which allows a user to enter a maximum of 10 characters. The program prints the count of how many times a given character occurs in the array.
/*Program to print how many times a given character occurs in an array*/
#include<stdio.h>
#include<conio.h>
void main()
{
char arr[10],ch,i,num,flag=0,count=0;
printf("How many characters you want to enter:");
scanf("%d",&num);
if(num>10)
{
printf("Size cannot be greater than 10.Try again...!");
}
else
{
/*Reading the array elements*/
printf("Enter the array elements:\n");
for(i=0;i<num;i++)
{
fflush(stdin);
scanf("%c",&arr[i]);
}
/*Reading the character to search in the array*/
printf("Enter the character you want to search:");
fflush(stdin);
scanf("%c",&ch);
/*Code to check if the character is available in the array or not*/
for(i=0;i<num;i++)
{
if(arr[i]==ch)
{
flag = 1;
count++;
}
}
if(flag==0)
printf("Given character is not available in the array.");
else
printf("Given character '%c' occurs %d times in the array",ch,count);
}
getch();
}
Sample input and output:
How many characters you want to enter:6
Enter the array elements:
a
b
c
a
d
a
Enter the character you want to search:a
Given character 'a' occurs 3 times in the array
No comments:
Post a Comment