Shopping spree exercise using arrays: Write a program that lets the user \"spend
ID: 3825812 • Letter: S
Question
Shopping spree exercise using arrays:
Write a program that lets the user "spend" up to $1,000 dollars or 5 items, whichever comes first, one item at a time. Do not allow the user to spend more than $1,000 dollars. Do not allow the user to purchase more than 5 items.
Step 1: Prompt for the price of each item. Store each item price in the array named prices. When the user has reached $1,000 or 5 items, print out how much was spent, how many items were bought, how much is left, and the average price. Print a table of the prices of the items bought.
Step 2: Expand your program to include item names. Prompt for each item name right before each price. Use another array to store the item names. (Hint: it's an array of strings. Look at the file attached here, pgm7-1string.cpp. Note that cin will only input one word.) Print a table of items bought, with the name and price of each one.
Explanation / Answer
// C++ code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
string name[1000];
double prices[1000];
int totalItems = 5;
int size = 0;
double price = 0;
double totalprice = 1000;
double currentprice = 0;
double remaining;
while(true)
{
cout << "Enter item name: ";
cin >> name[size];
cout << "Enter item price: ";
cin >> prices[size];
if ( (currentprice + prices[size]) > totalprice)
{
remaining = totalprice - currentprice;
break;
}
if(size >= totalItems)
break;
currentprice = currentprice + prices[size];
size++;
}
cout << " Name Price ";
for (int i = 0; i <= size; ++i)
{
cout << name[i] << " " << prices[i] << endl;
}
cout << " Number of items bought: " << (size+1) << endl;
cout << "Amount spent: " << currentprice << endl;
cout << "Amount left: " << remaining << endl;
cout << "Average price: "<< (currentprice/(size+1) ) << endl;
return 0;
}
/*
output:
Enter item name: poweder
Enter item price: 231
Enter item name: soap
Enter item price: 122
Enter item name: wheat
Enter item price: 241
Enter item name: oil
Enter item price: 331
Enter item name: tea
Enter item price: 123
Name Price
poweder 231
soap 122
wheat 241
oil 331
tea 123
Number of items bought: 5
Amount spent: 925
Amount left: 75
Average price: 185
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.