In this article, we are going to learn about how to search an element in an array in the C language. We will do this by using a simple for loop and a conditional statement like if-else. We will find the element in the array and if it exists then we will give the index of that element.If the element does not exist in the array then we will display an error message.so let us begin with our program example:
Steps to search an element in an array
- We are asking the user to enter the size of the array that they want.
- Once user enter the size we are taking the elements of this array as input from user.
- Then we are asking the user to tell which element he wants to search in this array.
C Program to search an element in an array
#include<stdio.h>
int main()
{
int arr[10], len;
int FindElem;
printf("Please enter the Size of array with max size 10: ");
scanf("%d", &len);
printf("Please enter the elements in this Array: ");
for(int i=0; i<len; i++)
scanf("%d", &arr[i]);
printf("Please tell which Element you want to Search: ");
scanf("%d",&FindElem);
for(int i=0; i<len; i++)
{
if(arr[i]==FindElem)
{
printf("The element %d is found at Index %d", FindElem, i+1);
return 0;
}
}
printf("The element is not Found in the array!");
return 0;
}
Output
Please enter the Size of array with max size 10: 5
Please enter the elements in this Array: 3 6 9 12 15
Please tell which Element you want to Search: 9
The element 9 is found at Index 3