Start learning free

LESSON 192 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Scala: Cart Sum with a for Loop

Practice Read the full explanation

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

You start with:

        val items = Array("Shirt", "Pants", "Shoes", "Hat")
        val prices = Array(25, 40, 60, 15)
        val quantities = Array(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 println(result).

Use val lines = scala.collection.mutable.ArrayBuffer[String]() and var total = 0 before the loop, then add each formatted line with +=.

Call lines.mkString("\n") at the end.

        val items = Array("Shirt", "Pants", "Shoes", "Hat")
        val prices = Array(25, 40, 60, 15)
        val quantities = Array(2, 1, 1, 3)

        val lines = scala.collection.mutable.ArrayBuffer[String]()
        var total = 0
        for (i <- items.indices) {
            val sub = prices(i) * quantities(i)
            total = total + sub
            lines.append(items(i) + " x" + quantities(i) + ": $" + sub)
        }
        lines.append("Total: $" + total)
        val result = lines.mkString("\n")
        println(result)

STEP 1 OF 9
    Ctrl + Enter to check

    SCALA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Scala, explained

    Problem overview

    The cart now holds several items. Three arrays run in parallel: items has the names, prices the unit prices and quantities how many of each. Position i in all three describes the same item. The program prints one receipt row per item, in the format Name xQ: $subtotal, where the subtotal is the price times the quantity, followed by a Total row that adds up every subtotal.

    For Array("Shirt", "Pants", "Shoes", "Hat"), prices Array(25, 40, 60, 15) and quantities Array(2, 1, 1, 3) the output is:

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

    The earlier versions handled one number at a time. This one introduces a loop that does the same work for every item, and a running total that grows as it goes.

    Approach: loop by position, collect rows, sum as you go

    Because the data sits in parallel arrays, the natural loop is over positions. items.indices is the range of valid positions, 0 up to the last one, so i takes the values 0, 1, 2, 3 and indexes all three arrays together. Each pass does three small things: compute the item's subtotal, add it to the running total, and record the row.

    The rows need somewhere to live until the end. A Scala Array has a fixed size, and a List is immutable, so the lesson uses an ArrayBuffer[String], a growable list. It is a val because the program only adds to the buffer and never replaces it. The total, on the other hand, is a var, because a new value is stored in it on every pass.

    The Total row belongs after the loop. It must run once, after every subtotal has been added, not once per item.

    Step by step

    1. Create lines, an empty scala.collection.mutable.ArrayBuffer[String]. The full name is needed because the mutable collections are not imported by default.
    2. Create total as a var starting at 0. It is the running sum.
    3. Write the loop for (i <- items.indices), with its closing brace right away. The steps below go inside it.
    4. Compute sub, this item's subtotal: prices(i) * quantities(i). Scala indexes arrays with parentheses, not square brackets.
    5. Add sub to total.
    6. Append the row with lines.append: the name, a space and x with the quantity, a colon, then $ and the subtotal.
    7. After the loop, append the Total row.
    8. Build result with lines.mkString("\n"). The argument is put between each two elements, so there is no newline after the last row.
    9. Print result with println.

    The solution in Scala

            val items = Array("Shirt", "Pants", "Shoes", "Hat")
            val prices = Array(25, 40, 60, 15)
            val quantities = Array(2, 1, 1, 3)
    
            val lines = scala.collection.mutable.ArrayBuffer[String]()
            var total = 0
            for (i <- items.indices) {
                val sub = prices(i) * quantities(i)
                total = total + sub
                lines.append(items(i) + " x" + quantities(i) + ": $" + sub)
            }
            lines.append("Total: $" + total)
            val result = lines.mkString("\n")
            println(result)

    Details that matter here:

    • Parentheses for indexing. prices(i) is a method call on the array, while square brackets in Scala are for type arguments such as the [String] in ArrayBuffer[String].
    • String plus Int. In items(i) + " x" + quantities(i) + ": $" + sub each + has a String on its left, so the numbers are converted to text as they are joined. The expression is evaluated left to right.
    • val with a mutable object. val lines means the name always points to the same buffer. The buffer's contents can still change, which is what append does.
    • items.indices is the same as 0 until items.length. It avoids writing the length by hand, so the loop follows the array if the cart grows.
    • mkString works on any collection and takes the separator. It is the usual way to join rows without a trailing separator.

    Following the loop

    For the starting data, the loop passes through four states. After the Shirt pass total is 50, after Pants 90, after Shoes 150 and after Hat 195. The last number is what the Total row prints. Each pass also adds exactly one row to lines, so by the end the buffer has five rows: four items and the total.

    Edge cases and common mistakes

    • Quantity 0. An item with quantity 0 still gets a row, with a subtotal of 0. For Array("Pen"), price 3 and quantity 0, the output is Pen x0: $0 and Total: $0.
    • Empty cart. With empty arrays the loop never runs, and the only row is Total: $0.
    • Arrays of different lengths. The loop follows items.indices, so a shorter prices or quantities array would throw an ArrayIndexOutOfBoundsException at the first missing position. The three arrays must describe the same items.
    • Putting the Total row inside the loop. That prints a total after every item instead of one at the end.
    • Replacing instead of adding. Writing total = sub keeps only the last subtotal. The line has to read total = total + sub, or the shorter total += sub.

    Testing

    A cart of one pen (price 3, quantity 0) and an empty cart both produce the outputs shown above. Try changing a quantity in the editor above and check that both the row and the total follow. The next version builds on this program.

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