Welcome back to Part 2 of our exploration of control flow in Rust! In the previous part, we learned how to make informed decisions using various conditional statements. Now, it's time to delve into loop statements, the workhorses of repetitive tasks in your programs.
What is a Loop?
A loop is a control flow structure that allows you to execute a block of code repeatedly until a specific condition is met, similar to a record player replaying a song until stopped. There are two main categories of loop statements in Rust:
1. for
Loops: Iterating a Fixed Number of Times or Over Collections
Think of a for
loop as a marathon runner completing a set number of laps or a chef iterating over a recipe's steps one by one.
Iterating a Fixed Number of Times:
for i in 1..=5 { // Includes 1 and 5 (5 iterations) println!("Iteration: {}", i); }
Iterating over a Collection:
let fruits = ["apple", "banana", "orange"]; for fruit in fruits { println!("I'm eating a {}", fruit); }
2. while
Loops: Repeating While a Condition is True
Think of a while
loop as a persistent explorer continuing a journey as long as a specific condition remains true, similar to searching for buried treasure until it's found.
let mut count = 0;
while count < 10 {
println!("Counting: {}", count);
count += 1; // Increment count on each iteration
}
Loop Control Statements: Taking the Wheel
Once you have a loop in motion, you might want to fine-tune its behavior. Rust provides statements for loop control:
break
: Exits the loop entirely, regardless of the current condition.for num in 1..=10 { if num % 3 == 0 { break; // Stop the loop when a number divisible by 3 is found } println!("Number: {}", num); }
continue
: Skips the current iteration of the loop and moves on to the next one.Rust
for letter in "hello world".chars() { if letter == ' ' { continue; // Skip spaces } println!("Letter: {}", letter); }
Nested Loops: Loops within Loops
Sometimes, your program needs multiple levels of repetition, like building a complex structure with layers or creating intricate patterns. Nested loops allow you to create loops within other loops, enabling intricate iterations.
for row in 1..=3 { // Outer loop iterates 3 times
for col in 1..=4 { // Inner loop iterates 4 times for each outer loop
print!("({},{}) ", row, col);
}
println!(); // Print a newline after each row
}
Practice Exercises:
Write a
for
loop that iterates from 1 to 10 and prints the square of each number.Create a
while
loop that continues to ask the user for their name until they enter "quit".Use a nested loop to print a 5x5 multiplication table.
Implement a program using a
for
loop that iterates over a vector of strings and prints only strings with a length greater than 5.Simulate a coin toss using a
while
loop andbreak
statement. The loop should continue until it lands on "heads" five times.
Coding Challenges:
Develop a text-based number guessing game. The program generates a random number between 1 and 100, and the user has to guess the number within a limited number of attempts. Use a
while
loop withbreak
and conditional statements for user interaction and feedback.Build a program that prints the Fibonacci sequence up to a user-specified limit. Use a loop and keep track of the previous two numbers to calculate the next one in the sequence.
Remember: Loops are fundamental tools for automating tasks in your Rust programs. By mastering different loop types and control statements, you can create powerful and dynamic applications. Experiment with various examples and challenges to solidify your understanding!