We can achieve many different outcomes with for loops.
It's all about tuning the start, end and step of the range.
For example, we can print all numbers from 2 through 6:
for i in 2..7 {
println!("{}", i);
}
The output of this code is:
2
3
4
5
6
Let's break down this code:
The range starts at
2, so we start iterating from number 2.The range end is
7(exclusive), so we stop at 6. We could've written2..=6and it would still be correct.We advance by
1each iteration automatically.
Assignment
Let's print all numbers from 3 through 10 using a for loop.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.