# Linear Search Algorithm in C Language

In this programming algorithm tutorial we will at how we can do a linear search in C language. A linear search algorithm using numbers is very easy to implement.

Take a look at the following source code:

``````
#include <stdio.h>

int main() {
int a;
int counter, num, numsearch;
int boolnum = 0;

printf("Enter the number of elements: ");
scanf("%d",&num);

printf("Enter the elements of the array: ");
for(counter=0;counter <= num-1;counter++) {
scanf("%d", &a[counter]);
}

printf("Enter the number to linear search for: ");
scanf("%d",&numsearch);

for(counter=0;counter <= num-1;counter++) {
if(a[counter] == numsearch) {
boolnum = 1;
break;
}
}
if(boolnum == 0)
printf("The number is not in the list.\n");
else
printf("The number is found.\n");

return 0;
}

``````

The result of the program will be something like this:

``````
Enter the number of elements: 4
Enter the elements of the array: 1 4 2 3
Enter the number to linear search for: 2
The number is found.

``````

As you can see, a linear search program is not that complex. We start by declaring some variables, an array of max 100 elements, some integers to hold various numbers and an integer that is used as a Boolean. Then we have some statements to get the number of elements we want to use and we are asking the user to enter a number for each element.

Then we are asking the user for a number to linear search for. The linear search algorithm is nothing else then looping though all element of the array and compare the element with the number we are looking for. If we find the number we set the Boolean to one and break out of the loop.

Last we check the Boolean so we can determine if the number was found in our array.

That’s all for this tutorial, as we have said earlier, a linear search example isn’t hard to implement.

Try to implement the same for character linear search. Try it yourself first, but a source code example of how to implement the linear search with characters can be downloaded here.

This entry was posted in Programming Algorithms. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! or use to share this post with others.

### There are currently 2 responses to “Linear Search Algorithm in C Language”

Why not let us know what you think by adding your own comment!

1. KASHIF RAZA on June 22nd, 2013:

nice

2. suresh on September 20th, 2013:

there is not much of this size is required for program