c program to write a Function search for searching an array elements

write a function for search which accept an array and return index of searched element. if not found then return -1


  /* write a function 
for search which accept an array
 and return index of searched
 element. if not found then return -1 */
#include <stdio.h>

int main() {
    // search function declaration
int search(int array[10],int ele,int size);
//variables
int i,array[10],key,ele,size;
//accept array size
printf("Enter array size");

scanf("%d",&size);
//input an array elements
    printf("\n Enter an array");
    
    for(i=0; i < size;i++)
    
    scanf("%d",&array[i]);
    //input element for search
    printf("\n enter to search element");
    
    scanf("%d",&ele);
    
    // search function call
    key=search(array,ele,size);
    
    //check key equal to -1
    if(key!=-1)
    
    /* if key not equal
to -1 then print key founded and key*/ 
    printf("\n key founded. key=%d",key);
    
    else

/* if key = -1 then print
key not founded */
printf("\n key not found");
    
    
}

//function defination part
//define search () function
int search(int array[10],int ele,int size)
{
    
    //local variables.
   int i; int flag=0;
   
   for(i=0; i < size;i++)
   {
       
    /*check if array elements match to the user entered element*/
       if(array[i]==ele)
       {
           /*if above condition true then assign flag value 1 */
           flag=1;
           
           //stop the loop  
           break;
       }
   }
   
   /* check condition flag equals to 1*/
   if(flag==1)
   
   /* if flag=1 then
 return i (index of element to
 search function)*/
       return (i);
       
       else
/* if flag not equals to 1 
then return -1 to search() function */
return (-1);

 }
  

output

search Array using Function


See Next C program

Comments