Linear Search

http://install4install.com

Searching in an array refers to finding the location of a particular element in the given array. It can be done in two ways :

Linear Search

Searching

Searching

It is done by comparing each and every element of array with the data item for which index needs to be found.The data item is compared with the items from 0 index till the last element of array.If the match is found then the index where items matched is returned to user.

Program

#include <stdio.h>

int main()
{
	int arr[5];
	int i;
	int element;
        //printf("enter the elements of array");	
	for(i=0;i<5;i++)
	{
		scanf("%d \t",&arr[i]);//Fig 1
	}
	// printf("Enter the element for which you want the search the respective index");
	scanf("%d",&element);
	for(i=0;i<5;i++)
	{
		if(arr[i] == element)

		printf("Location of this element is %d",i);
	}

	return 0;
}

Run

Explanation of above Program

  1. arr[5] is declared as an integer array.
  2. i is a variable to be used in for loop.
  3. element is the data item of int type which needs to be searched in array.
  4. scanf inside for loop is used to read all the values of array from user.Say user enters  100 200 130 140 150(Fig 1)
  5. User enters the element to be searched for in the array.Say 140.
  6. for loop starts and the initial value of i is 0,it will enter the loop as it less than 5(Condition is true).For further explanation refer Fig 2.

Fig 1 : An Array

Fig 3 :

Fig 2 :Explanation of Linear Search Program

TipIf element is present at two or more locations,then the respective indices will be returned to user.



Short URL: http://tinyit.cc/0d4829
Author: Cusp2207 on March 19, 2014
Category: Algorithms, Computer Science, Data Structures
Tags:

Leave a Reply

Last articles