Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

Repeating with While

Sometimes you want your program to do the same thing over and over again. That's where while loops come in! A while loop keeps running a block of code as long as a condition is true.

Your First While Loop

rust
fn main() {
let mut count = 1;
while count <= 5 {
println!("{}", count);
count += 1;
}
}

Let's break this down:

  • let mut count = 1; — We create a mutable variable (that's what mut means — it can change!)
  • while count <= 5 — Keep looping as long as count is 5 or less
  • count += 1; — Add 1 to count each time through the loop
  • No parentheses around the condition — Rust doesn't need them!
  • Curly braces {} are always required around the loop body

Counting Backwards

You can count down too! Just start high and subtract:

rust
fn main() {
let mut n = 5;
while n >= 1 {
println!("{}", n);
n -= 1;
}
println!("Go!");
}

The loop Keyword

Rust has a special keyword called loop that creates an infinite loop — it runs forever unless you tell it to stop with break:

rust
fn main() {
let mut num = 1;
loop {
println!("{}", num);
num += 1;
if num > 3 {
break;
}
}
println!("Done!");
}

The break statement immediately exits the loop. Without it, this loop would run forever!

Skipping with continue

Sometimes you want to skip the rest of the loop body and jump to the next round. That's what continue does:

rust
fn main() {
let mut i = 0;
while i < 10 {
i += 1;
if i % 2 == 0 {
continue;
}
println!("{}", i);
}
}

This prints only the odd numbers from 1 to 9. When i is even, continue skips the println! and goes back to the top of the loop.

Watch Out for Infinite Loops!

If the condition never becomes false, your loop will run forever. Always make sure something inside the loop changes the condition:

rust
fn main() {
let mut x = 1;
while x <= 5 {
println!("{}", x);
x += 1; // Without this line, x stays 1 forever!
}
}

Forgetting x += 1; would make this loop print 1 forever. Always double-check that your loop will eventually stop!

Summary

ConceptWhat it does
while condition { }Repeats while condition is true
loop { }Repeats forever (until break)
breakExits the loop immediately
continueSkips to the next iteration
let mutCreates a variable that can change

Now let's practice writing some loops!