Loop Control Flow in Rust

Introduction to Loop Control Flow in Rust

Hello! In this lesson, we'll explore the powerful concept of loop control flow in Rust. Control flow in loops allows you to manage the execution of code more effectively within your while and for loops. . Specifically, we'll delve into using conditionals inside loops, the loop construct, controlling loops with break and continue statements, and understanding their significance.

Control flow mechanisms are essential for building complex and functional logic in your programs. By the end of this lesson, you'll be proficient in using these tools to write more efficient and readable code.

Let's get started!

Conditionals Inside Loops

Let's first explore how to incorporate conditionals inside loops. This will help you perform specific actions based on dynamic conditions evaluated during each iteration.

fn main() {
    let mut num = 0;
    while num <= 10 {
        if num % 2 == 0 {
            println!("{} is even", num);
        } else {
            println!("{} is odd", num);
        }
        num += 1;
    }
}
/* Output:
    0 is even
    1 is odd
    2 is even
    3 is odd
    4 is even
    5 is odd
    6 is even
    7 is odd
    8 is even
    9 is odd
    10 is even
*/

In this example:

  • We initialize num to 0.
  • The while loop runs as long as num is less than or equal to 10.
  • Inside the loop, we use an if statement to check if num is even or odd, then print the approprita message.
  • We increment num by 1.

`loop` and `break` to Exit Loops

In Rust, an infinite loop can be created using the loop keyword. To stop the loop, use the break keyword to stop execution of the loop. This is useful when you want to stop a loop once a particular requirement is met. Let's take a look.

fn main() {
    let mut count = 0;
    loop {
        if count == 5 {
            break;
            println!("This does not get printed");
        }
        println!("Count is: {}", count);
        count += 1;
    }
}
/* Output:
    Count is 0
    Count is 1
    Count is 2
    Count is 3
    Count is 4
*/

In this example:

  • We initialize count to 0.
  • The loop runs indefinitely until the break condition is met.
  • When count equals 5, the break statement exits the loop.
  • The print statement inside the if block does not get executed because the loop stop execution
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal