Write a Program to find element in a array using Linear Search.

Working

In Linear Search one by one Compare Each Element with the Searching Element when the Element is found loop is break we get index|position of the element.

  • Make an Array
  • Set Found Flag as -1.
  • Loop Start
    • Compare Each Element with Search Element.
    • If Element is Match with Search Element.
    • Set Found Flag as Index of Element Search.
    • Break Loop.
  • End Loop
  • If Found Flag > -1
    • Element is Found
  • Else
    • Element is Not Found

Program

//Linear Search
#include<iostream.h>
#include<conio.h>
void display_array(int array[],int length){
for(int i=0;i<length;i++){
cout<<array[i];
(i==length-1)? cout<<".":cout<<",";
}
}
int find_number(int array[],int length,int search_number){
int found=-1;
for(int i=0;i<length;i++){
if(array[i]==search_number){
found=i;
break;
}
}
return found;
}
void main(){
clrscr();
int array[10]={12,34,21,39,65,48,36,11,58,23};
int number,found;
cout<<"\n Linear Search";
cout<<"\n -------------";
cout<<"\n Elements in a Array ";
display_array(array,10);
cout<<"\n Enter Number to be Search : ";
cin>>number;
found = find_number(array,10,number);
if(found>-1){
cout<<"\n Number Found at index of "<<found;
}else{
cout<<"\n "<<number<<" is not Found in Array ";
}
getch();
}

OUTPUT

FOUND

NOT FOUND

(Visited 104 times, 1 visits today)
Share with Friends :