-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Sunday 15 November 2015

Sequential search in C++

Sequential search

Sequential search is also called linear search or serial search.It is a simple to search an array for the desired value.It follows the following steps to search a value in an array:

Steps

  • Visit the first element of the array and compare its value with the required value.
  • If the value of the array matches with the required value,the search is complete.
  • If the value of array does not match,move to next element and repeat same process.
Loops are frequently used to visit elements of array for searching a value.You can start the counter variable of loop from 0 and move it to the last index of an array.

An example to demonstrate this concept is given below:

Source code


#include<iostream>
#include<conio.h>
using namespace std;
void main( )
{
int array[11]={10,20,30,40,50,60,70,80,90,100,110};
int i;
int n;
int location=-1;//location is initially null
cout<<"Enter value to search:";
cin>>n;
for(i=0;i<11;i++)   //you cannot write "for(i=0;i<=11;i++)" ........writing this will generate an error
if(array[i]=n)
loc=i;
if(loc== -1)
cout<<"Value not found in the array.";
else
cout<<"Value found at index"<<loc;
getch( );
}

Output

Enter value to search:40
Value found at index:3

Reference

The reference of this article has been taken from the book, "Object Oriented Programming in C++" by Robert Lafore.

No comments:

Post a Comment