Introduction
To find an element in an array is one of the primary concepts of programming. So in this blog, I am going to share a simple C Program that does the search of any value in an array and will return the place of that value in the array. In case that value is not found, it would print out an appropriate message instead.
Searching for a Value in an array in C programming
#include<stdio.h>
int main()
{
int num[]={12,34,56,78,19};
int pos=-1,value,i;
scanf("%d",&value);
for(i=0;i<5;i++)
{
if(value==num[i]){
pos=i+1;
break;
}
}
if(pos==-1){
printf("value is not common");
}
else printf("value %d is found at %d position",value,pos);
}
INPUT: 78 OUTPUT: value 78 is found at 4 positio
A fundamental task in programming is finding a value in an array, and the for loop is a popular iteration method.
Searching for a Value in an array in C programming
Time Complexity Analysis
In the worst case, in the last position or even not at all in the array.
In these cases, the loop iterates 5 times, exhibiting a time complexity of O(n), where n is the number of items in the array.
End Note
Linearly searching through a simple array is not in itself a method for this C code to find elements. It’s particularly useful for small datasets, while note-worthy performance improvements can be achieved with searching techniques like binary search (for sorted arrays) for much larger datasets.
Do you want a much-better-optimized version, or maybe you’d prefer it in Python? Your comment should say it all! 🚀