Start learning free

LESSON 124 OF 414 · WHILE LOOPS & FOR LOOPS

The While Loop in Rust: Syntax, Counters and Conditions

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while condition {
	instruction1
	instruction2
	...
}

Let's check an example:

let mut count = 1;
while count <= 5 {
	println!("I made a mistake");
	count += 1;
}
println!("Finished!");

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes.
	b. println!("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 2

2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes.
	b. println!("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 3

3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes.
	b. println!("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 4

4. Fourth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes.
	b. println!("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes.
	b. println!("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 6

6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No.
	b. Terminate the loop.


7. println!("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentially an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    RUST · WHILE LOOPS & FOR LOOPS

    The While Loop in Rust, explained

    What a while loop does

    A while loop repeats a block of code as long as a condition is true. Before every pass, Rust evaluates the condition. If it is true, the block runs. If it is false, the loop ends and the program continues with the line after the closing brace.

    The general shape is:

    while condition {
        // statements to repeat
    }

    Rust does not use parentheses around the condition, and the braces are always required, even when the body is a single statement. The condition must be a bool. Unlike some languages, Rust does not treat the number 1 or a non-empty string as "true": while 1 {} is a type error.

    A counter-controlled loop

    The most common use of while is a counter: a variable that starts at some value, is tested in the condition, and is changed inside the body. Here it is with output:

    let mut count = 1;
    while count <= 5 {
        println!("I made a mistake");
        count += 1;
    }
    println!("Finished!");

    This prints I made a mistake five times, then Finished!. Follow the values of count:

    1. count is 1. Is 1 <= 5? Yes, so print and make count 2.
    2. 2, 3, 4 and 5 pass the same test, and each pass adds 1.
    3. After the pass with 5, count is 6. Is 6 <= 5? No, so the loop ends.
    4. The program continues and prints Finished!.

    The body ran five times because the values 1, 2, 3, 4 and 5 pass the test. The test is also checked one extra time, with 6, to find out that it is time to stop. A while loop whose condition is false the very first time runs zero times.

    A while loop is like an if statement that jumps back and checks again after each run.

    Three parts every counter loop needs

    • Initialization: the counter gets its starting value before the loop.
    • Condition: a test on the counter, written after while.
    • Update: a statement in the body that moves the counter toward making the condition false.

    If any of the three is missing or wrong, the loop prints the wrong number of times or never stops.

    The exercise, step by step

    The lesson asks for the message I promise to learn coding. five times, using a loop. The steps build the loop one piece at a time.

    1. Declare the counter with let mut counter = 1;. The mut is needed: Rust variables are immutable by default, and this loop changes counter. Without mut, the update line fails to compile with cannot assign twice to immutable variable.
    2. Write the loop header with the condition counter <= 5. Starting at 1 and using <= means the body runs for 1, 2, 3, 4 and 5, which is five times.
    3. Print the message inside the braces with println!.
    4. Increase the counter with counter += 1;. Rust has no ++ operator, so += 1 is the way to write it.

    Put together:

    let mut counter = 1;
    while counter <= 5 {
        println!("I promise to learn coding.");
        counter += 1;
    }

    It prints the message on five lines.

    Common mistakes

    • Forgetting the update. If counter += 1; is missing, counter stays 1, the condition stays true, and the loop prints forever. The compiler may even warn that the variable does not need to be mutable, which is a hint that nothing in the loop changes it.
    • An off-by-one in the condition. Starting at 1 with counter < 5 prints four times. Starting at 0 with counter <= 5 prints six times. Decide the first value, the last value and whether the comparison includes the last one.
    • Forgetting mut. The compiler tells you and suggests adding it.
    • Using = instead of == or <= in the condition. A single = assigns; it is not a comparison.
    • Putting the update after the loop, outside the braces. Then it runs only once, after the loop has finished.

    Key takeaways

    • while condition { ... } checks the condition before each pass and repeats while it is true.
    • The condition has no parentheses, must be a bool, and the braces are required.
    • A counter needs an initial value, a test and an update, and it must be declared with let mut because it changes.
    • Use counter += 1; Rust has no ++.
    • If the condition is false from the start, the body never runs.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free