0
0
Rustprogramming~30 mins

Loop construct in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Loop construct in Rust
๐Ÿ“– Scenario: You are helping a small shop owner count the total number of items sold in a day. The shop owner has a list of daily sales numbers for each hour.
๐ŸŽฏ Goal: Build a Rust program that uses a loop construct to sum all the sales numbers and print the total.
๐Ÿ“‹ What You'll Learn
Create a vector called sales with the exact values: 5, 8, 12, 3, 7
Create a variable called total and set it to 0
Use a loop construct with an index variable i to iterate over sales
Add each sale to total inside the loop
Break the loop when all sales are added
Print the final total value
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Counting totals from lists of numbers is common in sales, inventory, and data analysis.
๐Ÿ’ผ Career
Understanding loops and data structures like vectors is essential for software development and data processing jobs.
Progress0 / 4 steps
1
Create the sales data
Create a vector called sales with the exact values 5, 8, 12, 3, 7.
Rust
Need a hint?

Use let sales = vec![5, 8, 12, 3, 7]; to create the vector.

2
Initialize the total counter
Create a variable called total and set it to 0 inside the main function, below the sales vector.
Rust
Need a hint?

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

3
Use a loop to sum sales
Use a loop construct with an index variable i starting at 0 to iterate over the sales vector. Inside the loop, add sales[i] to total. Break the loop when i reaches the length of sales.
Rust
Need a hint?

Start with let mut i = 0;. Use loop { ... }. Inside, check if i == sales.len() to break. Add sales[i] to total and increase i by 1.

4
Print the total sales
Add a println! statement to print the total variable after the loop ends.
Rust
Need a hint?

Use println!("Total sales: {}", total); to show the result.