Start learning free

LESSON 160 OF 409 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 - Cart Sum in C++

Practice

Use a for loop over parallel vectors to compute a running total across several items.

You start with:

vector<string> items = {"Shirt", "Pants", "Shoes", "Hat"};
vector<int> prices = {25, 40, 60, 15};
vector<int> quantities = {2, 1, 1, 3};

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with cout << result << endl.

Use a vector<string> lines; and an int total = 0; before the loop, then push_back each formatted line.

Build result by looping over lines and putting a "\n" between them.

vector<string> items = {"Shirt", "Pants", "Shoes", "Hat"};
vector<int> prices = {25, 40, 60, 15};
vector<int> quantities = {2, 1, 1, 3};

vector<string> lines;
int total = 0;
for (int i = 0; i < (int)items.size(); i++) {
    int sub = prices[i] * quantities[i];
    total = total + sub;
    lines.push_back(items[i] + " x" + to_string(quantities[i]) + ": $" + to_string(sub));
}
lines.push_back("Total: $" + to_string(total));
string result = "";
for (int i = 0; i < (int)lines.size(); i++) {
    if (i > 0) result += "\n";
    result += lines[i];
}
cout << result << endl;

STEP 1 OF 12
    Ctrl + Enter to check

    Shopping Cart V4 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free