Start learning free

LESSON 119 OF 348 · WHILE LOOPS & FOR LOOPS

For Loop II in Scala in Scala

Lesson

Scala for loops commonly iterate over a range.

The range decides where the loop starts, where it stops, and how it changes:

for (item <- range) {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The loop variable takes each value from the range.

  • The <- operator connects the loop variable to the range.

  • The range decides which values are visited.


Example:

for (i <- 0 until 4) {
	println("Hello world!")
}

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

Let's break down this code:

  • The range starts at 0.

  • until 4 means the range stops before 4.

  • So i takes the values 0, 1, 2, and 3.


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++ => 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++ => 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++ => 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++ => 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 Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free