Loops in Rust: for, while, and loop

 

Why Repeat Yourself When Rust Can Do It for You? 

Programming without loops is like making coffee one drop at a time.  Painful, right? Rust offers three looping mechanisms—for, while, and loop—to make repetition easy, efficient, and even fun! 

1. for Loop: The Smart Way to Iterate 

for is the go-to loop for iterating over ranges, collections, and anything iterable.

a) Basic for Loop

fn main() {
    for number in 1..=5 {
        println!("Counting: {}", number);
    }
}

 1..=5 means from 1 to 5 (inclusive)1..5 would mean from 1 to 4 (exclusive).

b) Looping Through an Array

fn main() {
    let fruits = ["Apple", "Banana", "Cherry"];
    for fruit in fruits.iter() {
        println!("I love {}!", fruit);
    }
}

 .iter() is used to iterate safely over an array.

2. while Loop: Keep Going Until It’s False 

Use while when looping until a condition is no longer true.

a) Basic while Loop

fn main() {
    let mut countdown = 5;
    while countdown > 0 {
        println!("T-minus {}...", countdown);
        countdown -= 1;
    }
    println!("Liftoff!");
}

Great for loops where the end condition isn’t predefined.

3. loop: The Infinite Power Loop

loop runs forever unless explicitly stopped with break.

a) Basic loop

fn main() {
    let mut count = 0;
    loop {
        println!("Looping forever... or not?");
        count += 1;
        if count == 3 {
            println!("Breaking out!");
            break;
        }
    }
}

Best for when you don’t know when to stop but control it inside the loop.

Wrapping Up 

Now you’ve mastered:  for loops for iterating over things.  while loops for condition-based repetition.  loop for infinite madness (unless you break).

Post a Comment

0 Comments