Start learning free

LESSON 191 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in C#: A Receipt with a for Loop and List

Practice Read the full explanation

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

You start with:

        string[] items = {"Shirt", "Pants", "Shoes", "Hat"};
        int[] prices = {25, 40, 60, 15};
        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 Console.WriteLine(result).

Use List<string> lines = new List<string>(); and an int total = 0; before the loop, then Add each formatted line.

Call string.Join("\n", lines) at the end.

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

        List<string> lines = new List<string>();
        int total = 0;
        for (int i = 0; i < items.Length; i++) {
            int sub = prices[i] * quantities[i];
            total = total + sub;
            lines.Add(items[i] + " x" + quantities[i] + ": $" + sub);
        }
        lines.Add("Total: $" + total);
        string result = string.Join("\n", lines);
        Console.WriteLine(result);

STEP 1 OF 9
    Ctrl + Enter to check

    C# · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in C#, explained

    Problem overview

    The cart is described by three arrays that line up by position: items holds the names, prices holds the price of one unit, and quantities holds how many units were bought. Position 0 is the shirt in all three arrays, position 1 is the pants, and so on.

    The program prints one receipt line for each item, in the format Name xQ: $subtotal, where the subtotal is the price times the quantity. A final line shows the total of all subtotals. For the starting data:

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

    The shirts cost 25 each and two were bought, so 50. The hats are 15 each and three were bought, so 45. The four subtotals sum to 195.

    Approach: one pass with a running total

    The same index i addresses the same item in all three arrays, so a single for loop over 0 to items.Length - 1 can read the name, the price and the quantity together. For each item the loop does three things: it computes the subtotal, adds it to a running total that started at 0, and appends a receipt line.

    The lines are collected in a List<string> rather than an array. An array has a fixed length chosen when it is created, while a list grows with each Add. The receipt gets one line per item plus the total line, and a list lets the code add them as they are produced. At the end, string.Join glues the lines into one text with a newline between each two.

    Step by step

    1. Create an empty List<string> named lines.
    2. Create total as an int set to 0.
    3. Loop by position. i runs from 0 while i < items.Length. For 4 items it takes the values 0, 1, 2 and 3.
    4. Compute the subtotal of the current item: prices[i] * quantities[i], stored in sub.
    5. Add it to the running total.
    6. Add the item's line with lines.Add: the name, a space and x, the quantity, a colon and space, a dollar sign and the subtotal, all joined with +.
    7. After the loop, add the total line. It goes outside the braces so it is added once, not once per item.
    8. Join the lines into result with string.Join("\n", lines).
    9. Print result with Console.WriteLine.

    The solution in C#

            string[] items = {"Shirt", "Pants", "Shoes", "Hat"};
            int[] prices = {25, 40, 60, 15};
            int[] quantities = {2, 1, 1, 3};
    
            List<string> lines = new List<string>();
            int total = 0;
            for (int i = 0; i < items.Length; i++) {
                int sub = prices[i] * quantities[i];
                total = total + sub;
                lines.Add(items[i] + " x" + quantities[i] + ": $" + sub);
            }
            lines.Add("Total: $" + total);
            string result = string.Join("\n", lines);
            Console.WriteLine(result);
    

    The C# details worth a closer look:

    • Arrays use Length, lists use Count. items.Length is the number of elements in the array. A List<T> reports its size with Count. Once the total line is added, lines.Count is 5.
    • for has three parts. int i = 0 runs once at the start, i < items.Length is checked before each round, and i++ runs after each round. The variable i exists only inside the loop.
    • A chain of +. The expression items[i] + " x" + quantities[i] + ": $" + sub starts with a string, so each + after it joins text, and the int values are converted as they are reached. An interpolated string says the same in one piece: $"{items[i]} x{quantities[i]}: ${sub}".
    • string.Join puts the separator between items only. The result has no newline after the last line. Console.WriteLine then adds the final line ending when it prints.
    • List<T> comes from System.Collections.Generic. string.Join accepts it because a list is a sequence of strings.
    • total = total + sub can also be written total += sub. The two mean the same thing.

    Edge cases and common mistakes

    • An empty cart. If all three arrays are empty, the loop never runs and the receipt is the single line Total: $0.
    • A single item. The receipt has two lines, the item and the total, with one newline between them and none after the total.
    • Arrays of different lengths. The loop is bounded by items.Length. If prices had fewer elements than items, the loop would reach a missing price and throw an IndexOutOfRangeException with the message Index was outside the bounds of the array. If it had more, the extra prices would be ignored silently.
    • Adding the total line inside the loop. The receipt would then contain a Total line after every item, each with a partial sum.
    • Starting the total at the wrong value. A running total must start at 0. Starting it elsewhere would shift the final sum by that amount.
    • Whole numbers only. int arithmetic is exact for whole dollars, but it wraps around silently if a product gets too large: with variables holding 100000 and 100000, the product comes out as 1410065408. A cart with realistic prices stays far from that limit.
    • Off-by-one in the loop. i <= items.Length would read one element past the end and throw the same exception. The condition is i < items.Length.

    Testing

    • The starting data gives the four item lines and Total: $195.
    • One item, "Shirt" at 25 with quantity 2, gives Shirt x2: $50 and Total: $50.
    • Empty arrays give Total: $0.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free