Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Saturday 16 March 2013

Linear Search In An Array C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to perform Linear Search In An Array, its Algorithm And C Code.

In computer sciencelinear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm; it is a special case of brute-force search. Its worst case cost is proportional to the number of elements in the list; and so is its expected cost, if all list elements are equally likely to be searched for. Therefore, if the list has more than a few elements, other methods (such as binary search or hashing) will be faster, but they also impose additional requirements.

Here is the C Code for Linear Search:


/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>
void main()
{
 int arr[10],num,i,n,found=0,pos=-1;
 clrscr();
 printf("Enter the number of elements in the array: ");
 scanf("%d",&n);

 printf("\nEnter the elements: \n");
 for(i=0;i<n;i++)
 {
  printf("arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 printf("\nEnter the number that has to be searched: ");
 scanf("%d",&num);

 for(i=0;i<n;i++)
 {
  if(arr[i]==num)
  {
   found=1;
   pos=i;
   printf("\n %d is found in the array at position = %d",num,i);
   break;
  }
 }
 if(found==0)
 printf("\ %d does not exist in the array",num);
 getch();
}


Output:

Linear Search C Code

Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Linear Search which is released under the Creative Commons Attribution-Share-Alike License 3.0


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: