How to find element?
This example will show you how to search an element in an Array using C program. Finding an element in an array is straight forward. You need to loop through the array elements and compare each element with the given or target element. If the element is found, an index of the element is returned otherwise a message with element not found is returned.
Prerequisites
Knowledge of C language
Search Functionality Implementation
The below search()
function takes four arguments:
int search(int *a, int n, int k)
*a
– pointer to an array
n
– size of the array
k
– the element to be searched in array
The full source code implementation for search functionality is given below:
#include<stdio.h>
int search(int *a, int n, int k){
int i;
for(i=0;i<n;i++){
if(a[i]==k){
return i;
}
}
return -1;
}
main(){
int i;
int a[50];
int searchIndex;
for(i=0;i<50;i++){
a[i]=i+100;
}
searchIndex = search(a,50,135);
if(searchIndex != -1){
printf("Search found at array index %d", searchIndex);
}else{
printf("Element not found in array");
}
return 0;
}
Testing Search Function
When you execute the above C program, you will see the following output:
Search found at array index 35