Saturday, 3 November 2018

A Program which uses linear searching? C++



Starts from the base index and compare it with the rest of the element of an array. If the serached index found, it returns 1 else it returns -1.


#include<iostream>

using namespace std;
/********************************************/
int linearSearch(int n[],int s,int size)
    {
        for(int i=0;i<size;i++)
        {
            if(n[i]==s)
            {
            return i;
            }
        }

        return -1;
    }

/*********************************************/
int main()
{
   int n[10];
   int s;
   int result;
   cout<<"Enter values in 'int' array"<<endl;
    for(int j=0;j<10;j++)
    {
    cin>>n[j];
    }
   cout<<"Enter number to search in array"<<endl;
   cin>>s;
   int size=sizeof(n)/sizeof(n[0]);
   result=linearSearch(n,s,size);

   if(result==-1)
   {
       cout<<"Value not found!"<<endl;
    }
    else
    {
    cout<<"value is on index"<<result<<endl;
    }
       return 0;

}

0 comments:

Post a Comment