Start learning free

LESSON 188 OF 667 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in C++: Parallel Vectors and a Running Total

Practice Read the full explanation

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

    C++ · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in C++, explained

    Problem overview

    The cart now holds several items, stored in three vectors that line up by position: items (names), prices and quantities. Position 0 of each vector describes the Shirt, position 1 the Pants, and so on. The program prints one receipt line per item in the form Name xQ: $subtotal, where the subtotal is the price times the quantity, and a final Total line. Everything is joined with newlines into one string, result.

    The starter data produces:

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

    The previous version handled one subtotal and shipping with an if/else. This one needs a loop.

    Approach: collect rows, then join them

    There are two jobs, and the lesson keeps them apart:

    1. Walk through the items by index. For each one, compute its subtotal, add it to a running total and store its receipt row in a vector<string> called lines.
    2. Add the Total row once, after the loop, because the total is only known when every item has been counted.
    3. Join the rows into result with a second loop, putting a newline between rows but not after the last one.

    A loop by index is the right tool here because the three vectors share the same index i. A loop that visits only the names would not give you the matching price and quantity.

    Step by step

    1. Create an empty vector<string> named lines to hold the rows as they are made.
    2. Create total and start it at 0. A running total always starts at zero.
    3. Open a for loop with i from 0 while i < (int)items.size().
    4. Compute sub as prices[i] * quantities[i].
    5. Add sub to total.
    6. Push this item's row onto lines: the name, a space and x, the quantity, a colon and space, a dollar sign and the subtotal. The two numbers go through to_string.
    7. After the loop, push the Total row, using total turned into text. This line is outside the braces so it happens once.
    8. Create result as an empty string. C++ has no ready-made join, so you build it yourself.
    9. Loop over lines by index, the same way as before.
    10. Add a newline before every row except the first (if (i > 0)), so rows are separated and nothing trails at the end.
    11. Add the row itself to the end of result.
    12. Print result with cout and endl.

    The solution in C++

    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;
    

    Details worth a closer look:

    • (int)items.size(). size() returns an unsigned type, and comparing it with a signed int such as i makes the compiler warn. Casting the size to int keeps the comparison between two signed numbers. It is safe here because the vectors are small.
    • Unsigned arithmetic is a trap. For an empty vector, items.size() - 1 does not give -1: it wraps around to 18446744073709551615 on a 64-bit build. The loop condition i < (int)items.size() avoids subtraction altogether.
    • One expression builds the row. items[i] + " x" + to_string(quantities[i]) + ": $" + to_string(sub) is evaluated left to right. It starts with a string, so every + after it joins a string with something that is already text. That is also why the name needs no to_string.
    • push_back adds one element at the end of the vector, which then grows by one.
    • The one-line if. if (i > 0) result += "\n"; has no braces, so it controls only that single statement. The next line, result += lines[i];, runs every time.

    How the running total grows

    Printing i, the subtotal and the total after each pass of the first loop, with the starter data, shows how total builds up:

    iItemsubtotal after the pass
    0Shirt5050
    1Pants4090
    2Shoes60150
    3Hat45195

    After the last pass, total holds 195, which is exactly what the final row needs. The Hat row shows why the multiplication matters: one hat costs 15, but three of them cost 45.

    Complexity

    Time: O(n) for n items. The first loop does a constant amount of work per item, and the second loop visits the n + 1 rows once each.

    Space: O(n) for the lines vector, plus the output string, which grows with the number of rows.

    Edge cases and common mistakes

    • Putting the Total row inside the loop. It would be added once per item and show partial totals.
    • Adding a newline after every row. The joined string would end with an extra newline, which then shows as an empty line after the output. The i > 0 test prevents that.
    • Forgetting to reset or initialise total. An uninitialised int holds an unspecified value.
    • Mixing up the indexes. Every vector must be read with the same i, which is what ties a price to its name.
    • An empty cart. With three empty vectors the loops never run and the output is just Total: $0.

    Testing

    CartOutput
    Shirt 25 x2, Pants 40 x1, Shoes 60 x1, Hat 15 x3The five lines above, ending with Total: $195
    Pen 3 x4Pen x4: $12, then Total: $12
    No itemsTotal: $0

    The next version builds on this program.

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