Search This Blog

Linear Search in C - C Program for Linear Search

Linear search simply means 'looking for an element in the whole array from one end to the other'. The searched element is compared with the first element of array first, then with the second, then with the third, so on upto the end of the array. This is time consuming when the array is pretty large. The time complexity is highest.The C program for linear search is given below.

#include<stdio.h>

void main()
{
int array[30], num, search, i;
printf("\nEnter the number of elements");
scanf("%i", &num);
printf("\nEnter the elements\n");
for (i = 0; i < num; i++)
{
scanf("%i", &array[i]);
}
printf("\nEnter the number to search for");
scanf("%i", &search);
for (i = 0; i < num; i++)
{
if (search == array[i])
printf("found at %i th position", i);
}
}

No comments: