Start learning free

LESSON 156 OF 679 · WHILE LOOPS & FOR LOOPS

For Loop II in Rust

Lesson

There is a more powerful way to use the for loop in Rust.

Rust has no three-part for (init; condition; update) loop. A for loop goes through every value of a range (or any other iterator), one value per iteration:

for i in range {
	instruction1;
	instruction2;
	...
}

Let's break down each component:

  • The loop variable (i) is created by the loop itself, with no let, and takes the next value from the range on every iteration.

  • The range (such as 0..4) says which values the variable takes: it starts at the first number and stops before the end number, which is excluded.

  • The loop stops by itself when the range runs out of values, and the variable moves to the next value automatically, so there is nothing to update.


Example:

for i in 0..4 {
	println!("Hello world!");
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The range 0..4 starts at 0, so the loop variable i starts counting from 0.

  • The range ends before 4, meaning the loop will run as long as the loop variable, i, is less than 4.

  • After each iteration, after running the code inside {}, i automatically moves to the next value, which is 1 larger.


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

0. The loop creates the variable i and sets it to the first value of the range, i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i moves to the next value => i = 1

2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i moves to the next value => i = 2

3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i moves to the next value => i = 3

4. Fourth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello world!".
	c. i moves to the next value => i = 4

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

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check