Introduction
Loops help you repeat actions many times without writing the same code again and again.
Loops help you repeat actions many times without writing the same code again and again.
loop {
// code to repeat
if condition {
break;
}
}loop creates an infinite loop unless you use break to stop it.
You can use break to exit the loop when needed.
loop {
println!("Hello!");
break;
}let mut count = 0; loop { count += 1; println!("Count: {}", count); if count == 5 { break; } }
This program prints numbers from 1 to 3 using a loop. It stops when the number is greater than 3.
fn main() {
let mut number = 1;
loop {
println!("Number is {}", number);
number += 1;
if number > 3 {
break;
}
}
}Loops can run forever if you forget to use break. Always make sure your loop can stop.
You can use continue inside loops to skip to the next repetition.
Loops repeat code multiple times without rewriting it.
loop creates an infinite loop that you stop with break.
Use loops to handle repeated tasks easily and clearly.
loop keyword do in Rust?loop keywordloop keyword in Rust creates a loop that repeats forever unless stopped.loop, you must use break inside it; otherwise, it runs infinitely.break is called. -> Option Bloop = infinite loop until break [OK]loop runs forever unless broken [OK]loop runs a fixed number of timesloop with for or whileloop stops automaticallyloop to create an infinite loop.while True { println!("Hello"); } uses while True which is invalid syntax in Rust. for i in 0.. { println!("Hello"); } uses for with an infinite range, but 0.. is not valid without an end. repeat { println!("Hello"); } uses repeat which does not exist in Rust. loop { println!("Hello"); } correctly uses loop.loop [OK]loop keyword for infinite loops in Rust [OK]while True which is invalid in Rustrepeat which doesn't existfor without a proper rangelet mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("{}", count);
}let mut i = 0;
loop {
if i == 5 {
break;
}
println!("{}", i);
}i is initialized but never changed inside the loop.i never increments, i == 5 is never true, so break is never reached, causing an infinite loop.loop to sum numbers from 1 to 5 in Rust?loop to add counter to sum.break to stop after 5break to exit loop.loop with a counter and break when counter > 5, adding each to sum. -> Option CPass the test and this pattern moves unknown