Start learning free

LESSON 121 OF 348 · WHILE LOOPS & FOR LOOPS

While loop: Printing more numbers in Rust in Rust

Lesson

Practice makes perfect! Let's check two more examples of printing numbers using the while loop.


Example 1:

Let's print all the even numbers from 4 through 14:

let mut i = 4;
while i <= 14 {
	println!("{}", i);
	i += 2;
}

The output of this program is:

4
6
8
10
12
14

Example 2:

We can also loop in reverse. Let's print all even numbers from 12 to 4 in decreasing order:

let mut i = 12;
while i >= 4 {
	println!("{}", i);
	i -= 2;
}

The output of this program is:

12
10
8
6
4

Assignment
Let's print all the odd numbers from 23 to 7 in decreasing order!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    Printing Numbers 2 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free