Start learning free

LESSON 168 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 - Cart Sum in Rust

Practice

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

You start with: an empty editor (no starter code). Declare this data yourself:

let items = vec!["Shirt", "Pants", "Shoes", "Hat"];
let prices = vec![25, 40, 60, 15];
let quantities = vec![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 let mut lines = Vec::new(); and let mut total = 0; before the loop, then push each formatted line.

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

        let items = vec!["Shirt", "Pants", "Shoes", "Hat"];
        let prices = vec![25, 40, 60, 15];
        let quantities = vec![2, 1, 1, 3];
        let mut lines = Vec::new();
        let mut total = 0;
        for i in 0..items.len() {
            let sub = prices[i] * quantities[i];
            total += sub;
            lines.push(format!("{} x{}: ${}", items[i], quantities[i], sub));
        }
        lines.push(format!("Total: ${}", total));
        let result = lines.join("\n");
        println!("{}", result);

STEP 1 OF 12
    Ctrl + Enter to check

    Shopping Cart V4 in Rust

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