Sunday 15 January 2012

linear search method


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr[10],i,num,flag=0;
cout<<"Enter ten numbers in the array"<<endl;
for(i=0;i<10;i++)
{
cin>>arr[i];
}
cout<<"Enter the number to search"<<endl;
cin>>num;
cout<<"The array elements are"<<endl;
for(i=0;i<10;i++)
{
cout<<arr[i]<<endl;
}

// loop to search the number
for(i=0;i<10;i++)
{
if(num==arr[i])
{
flag=1;
cout<<"The number is found at "<<i+1<<" location"<<endl;
break;
}
}
  if(flag==0)
  {
  cout<<"The number is not found"<<endl;
  }


getch();
}

2 comments:

  1. Why is that the number is found at i+1 and not i?

    ReplyDelete
    Replies
    1. Bcoz i starts from 0 so if you find data at 1st position,then you need to print " element found at"<<i+1 postion which means 0+1= 1st position

      Delete