Problem overview
The cart now holds several items, stored in three parallel arrays: items (names), prices and quantities. The item at position i in one array belongs with position i in the other two. The program must print one receipt line per item, then a total.
For the starting data, a shirt at 25 bought twice, pants at 40 once, shoes at 60 once and a hat at 15 three times, the output is:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
Each line reads Name xQ: $subtotal, where the subtotal is the price times the quantity. The last line adds all the subtotals.
Approach: one pass with a running total
Every item needs the same work: multiply, add to a total, format a line. A for loop over the positions does that once per item. Two things live outside the loop and survive from one round to the next: a mutable list that collects the lines, and a var that holds the total so far.
The loop goes over items.indices, which is the range of valid positions, 0 up to the last one. Using positions rather than the names themselves lets the loop reach into prices and quantities with the same i.
A loop like this is the usual way to turn a list of records into a report. Each round does the same three jobs: compute a value from the arrays, fold it into the running total, and record a line of output. The first version of the cart handled one product. The loop is what lets the same code handle four, or forty, without being rewritten.
Parallel arrays are the simplest way to keep related data together when you are just starting. Their weakness is that nothing links the three arrays except the position, so they must be kept the same length and in the same order by hand.
Step by step
- Create
lines.mutableListOf<String>()makes an empty list that can grow. It is avalbecause the program adds to this list and never swaps it for another. - Create
total. It is avarstarting at 0, because it changes on every round. - Write the loop over
items.indices, with the closing brace in place before filling the body. - Compute
sub. Inside the loop, it isprices[i] * quantities[i], this item's subtotal. - Update the total. Add
subtototal. - Add the item's line. Glue together the name,
" x", the quantity,": $"and the subtotal, and add the result tolines. - Add the total line after the loop. It runs once, when every subtotal is already in the total.
- Join the lines.
lines.joinToString("\n")puts a newline between each two elements, so the result has no newline after the last line. - Print
result.
The solution in Kotlin
val items = arrayOf("Shirt", "Pants", "Shoes", "Hat")
val prices = intArrayOf(25, 40, 60, 15)
val quantities = intArrayOf(2, 1, 1, 3)
val lines = mutableListOf<String>()
var total = 0
for (i in items.indices) {
val sub = prices[i] * quantities[i]
total = total + sub
lines.add(items[i] + " x" + quantities[i] + ": $" + sub)
}
lines.add("Total: $" + total)
val result = lines.joinToString("\n")
println(result)
Kotlin details worth a closer look:
- Three kinds of array.
arrayOf("Shirt", ...)makes anArray<String>.intArrayOf(25, ...)makes anIntArray, a compact array of plain integers. Both are indexed with[i]and have.indices. indicesis a range. For four items it covers 0, 1, 2 and 3. There is no off-by-one risk of the kind that0..items.sizewould bring, since that range would include 4 and read past the end.String + Int. Initems[i] + " x" + quantities[i]the left side is already aString, so each+turns the next number into text. A literal"$"followed by a quote is a dollar sign, not a template.- Why the list is a
val.valmeans the variable can't be reassigned, not that the list is frozen.lines.add(...)changes the list the variable points to.totalhas to be avarbecause the loop assigns to it. total = total + subcan also be writtentotal += sub. Both do the same thing.
Running time grows in step with the number of items: one pass, a constant amount of work per item.
Edge cases and common mistakes
- The total line inside the loop. It would print once per item instead of once at the end.
- Arrays of different sizes. The loop trusts that all three arrays are as long as
items. Ifpriceswere shorter, the program would stop with an index error on the first missing position. - Trailing newline. Joining with
joinToString("\n")avoids a blank line at the end, since the separator goes only between elements. - Empty cart. With empty arrays, the loop doesn't run and the output is just the total line.
Testing
Try a cart with one item: arrayOf("Pen"), prices intArrayOf(4) and quantities intArrayOf(5). The program prints:
Pen x5: $20
Total: $20
With all three arrays empty, the program prints only:
Total: $0
