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
- Create an empty
List<string>namedlines. - Create
totalas anintset to 0. - Loop by position.
iruns from 0 whilei < items.Length. For 4 items it takes the values 0, 1, 2 and 3. - Compute the subtotal of the current item:
prices[i] * quantities[i], stored insub. - Add it to the running total.
- Add the item's line with
lines.Add: the name, a space andx, the quantity, a colon and space, a dollar sign and the subtotal, all joined with+. - After the loop, add the total line. It goes outside the braces so it is added once, not once per item.
- Join the lines into
resultwithstring.Join("\n", lines). - Print
resultwithConsole.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 useCount.items.Lengthis the number of elements in the array. AList<T>reports its size withCount. Once the total line is added,lines.Countis 5. forhas three parts.int i = 0runs once at the start,i < items.Lengthis checked before each round, andi++runs after each round. The variableiexists only inside the loop.- A chain of
+. The expressionitems[i] + " x" + quantities[i] + ": $" + substarts with astring, so each+after it joins text, and theintvalues are converted as they are reached. An interpolated string says the same in one piece:$"{items[i]} x{quantities[i]}: ${sub}". string.Joinputs the separator between items only. The result has no newline after the last line.Console.WriteLinethen adds the final line ending when it prints.List<T>comes fromSystem.Collections.Generic.string.Joinaccepts it because a list is a sequence of strings.total = total + subcan also be writtentotal += 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. Ifpriceshad fewer elements thanitems, the loop would reach a missing price and throw anIndexOutOfRangeExceptionwith 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
Totalline 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.
intarithmetic 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.Lengthwould read one element past the end and throw the same exception. The condition isi < items.Length.
Testing
- The starting data gives the four item lines and
Total: $195. - One item,
"Shirt"at 25 with quantity 2, givesShirt x2: $50andTotal: $50. - Empty arrays give
Total: $0.
