Search an element by index in C array |Example code

C-Array

In this article, we are going to search an element entered by the user in the array. We will search the element to check if it exists in the array or not. If it exists then we will display the message with the position of the element in the array.

C Program to Search an element by index in Array

#include<stdio.h>
int main()
{
   int arr[10], num, element;
   int i, found=0, count=0, pos=0;

   printf("Please enter the Size of array with Max size 10: ");
   scanf("%d", &num);

   
    printf("Please enter the elements in this Array: ");
   for(i=0; i<num; i++) 
      scanf("%d", &arr[i]);

   printf("Please enter the elements You want to Search: ");
   scanf("%d", &element);

   for(i=0; i<num; i++)
   {
     if(arr[i]==element)
     {
       count++;

       printf("Element %d is found at position %d \n",element,i+1);

     }
   }

   if(count==0) 
      printf("\nElement %d is not found in the array", element);
   else 
      printf("\nElement %d is found %d times in the array",element,count);

   return 0;
}

Output

Please enter the elements in this Array: 1
2
1
4
Please enter the elements You want to Search: 1
Element 1 is found at position 1 
Element 1 is found at position 3 

Element 1 is found 2 times in the array