Below is a C program which allows an user to enter a maximum of 10 characters . It also allows an user to search whether a given character is
available in the array or not. If the given character is available, the program displays
the index within the array at which the character is found.
/*Program to search for a given character in an array*/
#include<stdio.h>
#include<conio.h>
void main()
{
char arr[10],ch,i,num,flag=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)
{
printf("%c is found at index %d\n",ch,i);
flag = 1;
}
}
if(flag==0)
printf("Given character is not available in the array.");
}
getch();
}
Sample input and output:
How many characters you want to enter:5
Enter the array elements:
a
b
c
d
e
Enter the character you want to search:b
b is found at index 1
No comments:
Post a Comment