C Program to Search an Element in an Array

C program to search an element in an array | Here we will write a c program to search an element in an array using linear search. There are many searching algorithms to find an element in an array. In this program, we will use a linear search.

Program description:- Write a C program to search an element from the list of numbers. If element found then display it with the position in the array.

Search an Element in Array using C

// linear search
int main()
   int a[100], n, element, pos=0;
   int i;

   printf("Enter array size [1-100]: ");
   scanf("%d", &n);

   printf("Enter array elements: ");
   for(i=0; i<n; i++)scanf("%d", &a[i]);

   printf("Enter element to search: ");

   for(i=0; i<n; i++)
       printf("%d found at position %d", element, i+1);
       return 0;

   printf("%d not found.", element);
   return 0;

Output for the different test-cases:-

Enter array size [1-100]: 5
Enter array elements: 5 20 9 85 4
Enter element to search: 20
20 found at position 2

Enter array size [1-100]: 3
Enter array elements: 9 5 1
Enter element to search: 8
8 not found.

Enter array size [1-100]: 6
Enter array elements: 1 2 1 2 3 1
Enter element to search: 2
2 found at position 2

To find an element in the array we use for loop, if statement and equality operator. If the array element is equal to the searching element then it will be displayed with position and program completed because of return 0; next lines does not execute. But if element not found then if condition not executed and statements after for loop also executed.

In the last input/output example we can observe that there is more than one element but our program display only first position. We can also write a program where we can search position of nth times occurred element in the array.

More C Program Examples on Arrays

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Follow Us
Instagram • Twitter • Youtube • Linkedin • Facebook • Pinterest • Telegram

Leave a Comment

Your email address will not be published. Required fields are marked *