Linear search function for search term presence and location – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#1632 siteicon   siteicon   siteicon  

Problem Statement - Linear search function for search term presence and location

Write a function linsearch(int [],int, int) which searches for the term 23 in the given integer array [12,19,23,3,2] and returns its position in the array. This array should be initialised in the calling function and then passed as reference to the given function. Show implementation also.

Solution

TC++ #1632

#include <iostream>
using namespace std;
int linsearch(int [],int, int);
int main()
{
int ar[]={12,19,23,3,2};
int sr=linsearch(ar,5,23);
if(sr>0)
cout<<"Element found at position"<<sr<<endl;
else
cout<<"Element not found"<<endl;
}

int linsearch(int a[],int size,int term)
{
for(int i=0;i<size;i++)
{
if(a[i]==term) return i+1;
}
return 0;
}

Test it !

Run Output

Element found at position 3

if(a[i]==term) return i+1;
i+1 will return the position as i will contain the index in the array. If element is not found 0 will be returned.


Share

sunmitra| Created: 4-Dec-2017 | Updated: 1-Jan-2018|






Back