Start learning free

LESSON 153 OF 679 · WHILE LOOPS & FOR LOOPS

While Loop: Printing Numbers in Rust

Lesson

We can achieve many different outcomes with while loops.

For example, we can print all the numbers from 0 through 4:

let mut i = 0;
while i < 5 {
	println!("{}", i);
	i += 1;
}

The output of this program is:

0
1
2
3
4

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

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 5 true? <=> Is 0 < 5 true? Yes.
	b. println!("{}", i); => Output: 0
	c. i += 1; => i = 1

2. Second iteration:
	a. Is i < 5 true? <=> Is 1 < 5 true? Yes.
	b. println!("{}", i); => Output: 1
	c. i += 1; => i = 2

3. Third iteration:
	a. Is i < 5 true? <=> Is 2 < 5 true? Yes.
	b. println!("{}", i); => Output: 2
	c. i += 1; => i = 3

4. Fourth iteration:
	a. Is i < 5 true? <=> Is 3 < 5 true? Yes.
	b. println!("{}", i); => Output: 3
	c. i += 1; => i = 4

5. Fifth iteration:
	a. Is i < 5 true? <=> Is 4 < 5 true? Yes.
	b. println!("{}", i); => Output: 4
	c. i += 1; => i = 5

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

Assignment
Let's print all numbers from 3 to 10 using a while loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check