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.
Free plan: 30 tutor messages. Premium is unlimited.