0
0
Rustprogramming~15 mins

For loop in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Using a For Loop in Rust
๐Ÿ“– Scenario: You are helping a small shop owner who wants to list the prices of some fruits they sell. You will write a Rust program to show each fruit and its price.
๐ŸŽฏ Goal: Build a Rust program that uses a for loop to print each fruit and its price from a list.
๐Ÿ“‹ What You'll Learn
Create a vector called fruits with tuples of fruit names and prices
Create a variable called count to count the number of fruits
Use a for loop with variables name and price to iterate over fruits
Print each fruit name and price inside the loop
Print the total number of fruits after the loop
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
For loops are used to process lists of items like products, prices, or user data in many programs.
๐Ÿ’ผ Career
Understanding for loops is essential for software development jobs where you handle collections of data efficiently.
Progress0 / 4 steps
1
Create the fruit list
Create a vector called fruits with these exact tuples: ("Apple", 3), ("Banana", 2), ("Cherry", 5).
Rust
Need a hint?

Use let fruits = vec![("Apple", 3), ("Banana", 2), ("Cherry", 5)]; to create the list.

2
Add a count variable
Add a variable called count and set it to 0 to count the fruits.
Rust
Need a hint?

Use let mut count = 0; to create a variable that can change.

3
Use a for loop to print fruits
Use a for loop with variables name and price to iterate over fruits.iter(). Inside the loop, print the fruit name and price using println!("{}: ${}", name, price); and increase count by 1.
Rust
Need a hint?

Use for (name, price) in fruits.iter() to loop. Use count += 1; to add one each time.

4
Print the total count
After the loop, print the total number of fruits using println!("Total fruits: {}", count);.
Rust
Need a hint?

Use println!("Total fruits: {}", count); after the loop to show the count.