Write a C function that receives i an array of characters an
Solution
#include <stdio.h>
#include <string.h>
int search(char arr[], char c); //declaration of function
int main()
{
char text[20]; //var to store char array
char c; //var to store the character
int index;
printf(\"Enter the arr: \");
scanf(\"%s\", text);//read the characters from the user
getchar();
printf(\"Enter the character:\");
scanf(\"%c\", &c);//read a character from the user
index=search(text,c); //call to the function search
if(index==-1){
printf(\"character not found. Index= %d\",index);
}else{
printf(\"character found. Index= %d\",index);
}
return 0;
}
//function to return the index of the found character. index starts from 0
int search(char arr[], char c){
int index=-1;
int len= strlen(arr);//length of the passed array
for(int i=0;i<len;i++){
if(arr[i]==c){ // if the char is found then index =i and break from the loop
index=i;
break;
}
}
return index;
}
/******************output *********/
sh-4.3$ gcc -o main *.c
sh-4.3$ main
Enter the arr: world
Enter the character:o
character found. Index= 1sh-4.3$
sh-4.3$ main
Enter the arr: world
Enter the character:e
character not found. Index= -1
/******************output ends *********/
Feel free to ask any question. God bless you
