In this article, you will understand the concept of linear search in C programming using arrays and functions.
Searching is the process of finding particular value in an array. There are two ways of searching an array:
Linear search is a searching algorithm which is used to detect the presence of a number in an array and if present, it locates its position in that array.
This algorithm compares each element of the array with the search query comparing every element until the number is found and located.
Please go through following C programming articles to understand the concept of the following program (implementation of a linear searching algorithm).
This program generates data that are stored in an array and find the value entered by the user in that array.
#include <stdio.h>
#define SIZE 100
//function prototype
int linearSearch(int a[], int query, int size);
int main()
{
int data[ SIZE ], i, temp;
int searchQuery; //value to search in the array
//generate some data
for (i = 0; i < SIZE; ++i)
{
data[ i ] = 2 * i;
}
printf("Enter integer to search for: ");
scanf("%d", &searchQuery);
//finding searchQuery in array data
temp = linearSearch(data, searchQuery, SIZE);
//condition for displaying result
if ( temp != -1)
printf("Found value in element %d.", temp);
else
printf("Value not found.");
return 0;
}
//Linear search function
int linearSearch(int a[], int query, int size)
{
int j; //counter variable
//loop through array
for (j = 0; j < size; ++j)
{
if ( a[ j ] == query)
{
return j; //return location of value
}
}
return -1; //value not found
}
[adsense1]
Output
#1
#2
Explanation
In the above program, we have generated multiples of 2 and stored in the array data
.
There is the user-defined function called linearSearch( )
that searches the user query in an array.