Start learning free

LESSON 123 OF 348 · WHILE LOOPS & FOR LOOPS

For Loop II in Rust in Rust

Lesson

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

For loops can be declared with three optional expressions separated by semicolons:

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

Let's break down each component:

  • The initialization statement is executed one time only before the loop starts and is typically used to define and set up the iterator variable.

  • The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing.

  • The iteration statement is executed at the end of each loop iteration, prior to the next condition check and is usually used to update the iterator variable.


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 initialization statement is let i = 0. We create and initialize the iterator variable i so the loop starts counting from 0.

  • The condition statement is i < 4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • The iteration statement is i += 1. This means that after each iteration, after running the code inside {}, i will get increased by 1.


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

0. Creates and initializes a variable 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 += 1 => 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 += 1 => 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 += 1 => i = 3

4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes.
	b. Run the code inside {}. Print "Hello World".
	c. i += 1 => 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

    The For Loop 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