Start learning free

LESSON 126 OF 348 · WHILE LOOPS & FOR LOOPS

Looping In Reverse in Rust in Rust

Lesson

A for loop can also count backwards, as long as we define the right conditions. For example:

for i in (3..=7).rev() {
	println!("{}", i);
}

The output of this code is:

7
6
5
4
3

Let's break down this code:

  • The range is (3..=7), so we start iterating from number 7 (in reverse).

  • We end at 3 (the lower bound of the range). We could've written (3..8).rev() with an exclusive upper bound and it would still be correct.

  • The .rev() call reverses the range, so we decrease our number by 1 every time.


Assignment

Let's print all numbers from 5 through -5 in decreasing order.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Looping In Reverse 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