Array search program in C

Very often we encounter a situation where we have to search for a given target value in a list of values. Simple value types like integers are stored in arrays. This program demonstrates how to do a search within an array by using a method called linear search.

Linear search, also called as ‘Sequential search’ is a technique of finding a target value within a list. It sequentially checks each element of the list with target value until a match is found or the list is exhausted. This approach may be very inefficient to be used in practical problem solving. However, this is very easy to understand and implement. You can read more about linear search.

This program implements linear search to search for a given integer key in an integer array. We have many more C programs that deal with arrays. See more Programs on Arrays in C.

The Program

#include <stdio.h>
#include <conio.h>
void main()
{
int array[10];
int i, N, keynum, found=0;
printf("Enter the value of N\n");
scanf("%d",&N);
printf("Enter the elements one by one\n");
for(i=0; i<N ; i++)
{
scanf("%d",&array[i]);
}
printf("Input array is\n");
for(i=0; i<N ; i++)
{
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d", &keynum);
for ( i=0; i < N ; i++)
{
if( keynum == array[i] )
{
found = 1;
break;
}
}
if ( found == 1)
printf("Element found in the given array");
else
printf("Element was not found in the array");
} /* End of main */

Sample Output


Related programs

 

To get regular updates on new C programs, you can Follow @c_program. You can discuss these programs on our Facebook Page. Like to get updates right inside your feed reader? Grab our feed!

(c) www.c-program-example.com

Leave a Reply