+ 2
How to do linear search in c++??
I am making a structure of inventory and I want to perform a linear search in c++ on basis of their price or id in inventory structure
1 Answer
+ 3
Use a for loop to compare till you get to the value.
Eg :
struct item{
// Your items and types here.
float price; int id: };
item inven[10];
// Array of items to search in.
// Set up values respectively for
// each element.
// Search based on price:
float pr;
cout<<"Search for item with price : ";
cin>>pr;
for(int i=0;i<10;i++)
{
if(inven[i].price==pr)
{/*Do things*/}
}
// Search based on id:
int idr;
cout<<"Search for item with id : ";
cin>>idr;
for(int i=0;i<10;i++)
{
if(inven[i].id==idr)
{/*Do things*/}
}