Menu
Coddy logo textTech

Enhanced For Loop

Part of the Fundamentals section of Coddy's Rust journey — lesson 66 of 75.

There are different ways to iterate over an array, here are some of them:

Consider the following array:

let numbers = [1, 2, 3, 4, 5];
  • Direct Iterator:

    for num in numbers.iter() {}
    // Values: 1, 2, 3, 4, 5
  • Index & Value:

    for (index, value) in numbers.iter().enumerate() { }
    // Values: (0,1), (1,2), (2,3), (3,4), (4,5)
  • Slices of specific size:

    for chunk in numbers.chunks(2) { }
    // Values: [1,2], [3,4], [5]
  • Iterate with mutation:

    for num in numbers.iter_mut() { 
    	*num *= 2;
    }
    // Array becomes: [2, 4, 6, 8, 10]
challenge icon

Challenge

Easy

Create a program that processes a shopping list with items and their prices, and provides different views of the data.

The program should:

  1. Print each item number and price (using enumerate)
  2. Print the prices in pairs (using chunks) as "bundle deals"
  3. Apply a 10% discount to all prices (using iter_mut)
  4. Print the final discounted prices

Cheat sheet

Different ways to iterate over arrays in Rust:

Direct Iterator:

for num in numbers.iter() {}
// Values: 1, 2, 3, 4, 5

Index & Value with enumerate:

for (index, value) in numbers.iter().enumerate() { }
// Values: (0,1), (1,2), (2,3), (3,4), (4,5)

Slices of specific size with chunks:

for chunk in numbers.chunks(2) { }
// Values: [1,2], [3,4], [5]

Iterate with mutation using iter_mut:

for num in numbers.iter_mut() { 
    *num *= 2;
}
// Array becomes: [2, 4, 6, 8, 10]

Try it yourself

fn main() {
    let mut prices = [2.75, 1.50, 5.00, 3.5, 4.1, 2.25, 7.9];

    println!("Original Prices:");
    // TODO: Use enumerate to print each item number and price
    // Expected: "Item 1: $2.99" etc.


    println!("\nBundle Deals:");
    // TODO: Use chunks to print pairs of prices and their sums
    // Expected: "Bundle 1: $2.99 + $1.50 = $4.49" etc.


    // TODO: Use iter_mut to apply 10% discount to all prices


    println!("\nPrices after 10% discount:");
    // TODO: Print final prices after discount
    // Expected: "$2.69" etc.

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals