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

Rewrite the following program so that it throws an appropriate exception when a

ID: 655675 • Letter: R

Question

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

C++ only.

Please make sure your code works before posting.

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;

}

Explanation / Answer

Program:

#include <iostream>

#include <string.h>

using namespace std;

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

{

int f=0, ans;

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

{

if(names[i]==target){

               f=1;

               ans=ids[i];

               break;

}

}

if(f==0){

               throw " Exception!!! Product not found ";

               //return -1;   // Not found

}

return ans;

}

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;

}

Output:

Product Id for mouse: 8

Product Id for camera:13

Product Id for laptop: Exception!! Product not found

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote