Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

int getProductID(int ids[], string names [], int numProducts, string target) { f

ID: 655287 • Letter: I

Question

int getProductID(int ids[], string names [],

int numProducts, string target)

{

for (int i=0; i < numProducts; i++)

{

if (names[i] == target)

return ids[i];

}

return -1; // Not found

int main() // Sample code to test the getProductID function

{

int productIds[] = { 4, 5, 8, 10, 13 };

string products[] = { "computer", "flash drive",

"mouse", "printer", "camera" };

cout << getProductID(productIds, products, 5, "mouse") << endl;

cout << getProductID(productIds, products, 5, "camera") << endl;

cout << getProductID(productIds, products, 5, "laptop") << endl;

return 0;

}

Rewrite the program so that it throws an appropriate exception when a product is not found instead of returning -1.

Explanation / Answer

#include <iostream>

#include <string.h>

using namespace std;

int getProductID(int ids[], string names[20], int numProducts, string target)

{

int exp=0, res;

for (int i=0; i < numProducts; i++)

{

if(names[i]==target)
{

exp=1;

res=ids[i];

break;

}

}

if(exp==0)
{

throw " Exception!!! Product not found ";

  
}

return res;

}

int main() // Sample code to test the getProductID function

{

int productIds[] = { 4, 5, 8, 10, 13 };

string products[20] = { "computer", "flash drive","mouse", "printer", "camera" };

try
{

cout<<endl<< "Product Id for mouse: ";

cout<<getProductID(productIds, products, 5, "mouse");

cout<<endl<< "Product Id for camera:";

cout<<getProductID(productIds, products, 5, "camera");

cout<<endl<< "Product Id for laptop:";

cout<<getProductID(productIds, products, 5, "laptop");

}

catch(const char* msg)

{

cerr << msg << endl;

}

return 0;

}