How to do linear search in c++?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

25th Jan 2018, 9:34 AM
Harsh Sharma
Harsh Sharma - avatar
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*/} }
25th Jan 2018, 12:49 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar