Start learning free

LESSON 120 OF 414 · WHILE LOOPS & FOR LOOPS

The While Loop in Scala: Repeating Until a Condition Fails

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while(condition) {
	instruction1
	instruction2
	...
}

Let's check an example:

var count = 1
while(count <= 5) {
	println("I made a mistake")
	count += 1
}
println("Finished!")

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

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

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes. 
	b. println("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 2
	
2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes. 
	b. println("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 3
	
3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes. 
	b. println("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 4
	
4. Fourth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes. 
	b. println("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes. 
	b. println("I made a mistake"); => Output: I made a mistake
	c. count += 1; => count becomes 6
	
6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No. 
	b. Terminate the loop.

	
7. println("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentially an if statement that repeats itself over and over until the condition becomes false.


Assignment

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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · WHILE LOOPS & FOR LOOPS

    The While Loop in Scala, explained

    What a while loop does

    A while loop runs a block of statements again and again as long as a condition is true. Before every pass, Scala evaluates the condition. If it is true, the block runs once and the condition is checked again. If it is false, the loop ends and the program continues with the line after the closing brace.

    while (condition) {
        instruction1
        instruction2
    }
    

    The condition is an expression of type Boolean, such as count <= 5. You can think of a while loop as an if statement that jumps back and asks its question again after each run of the block.

    A worked example

    var count = 1
    while (count <= 5) {
        println("I made a mistake")
        count += 1
    }
    println("Finished!")
    
    I made a mistake
    I made a mistake
    I made a mistake
    I made a mistake
    I made a mistake
    Finished!
    

    Here is what happens, step by step:

    1. count is created with the value 1.
    2. Is 1 <= 5? Yes. Print the message, then count becomes 2.
    3. Is 2 <= 5? Yes. Print again, count becomes 3.
    4. The same happens while count is 3, 4 and 5, for five messages in total, and the last pass leaves count at 6.
    5. Is 6 <= 5? No. The loop ends without running the block.
    6. println("Finished!") runs once, because it is after the loop.

    Every counting loop has the same three parts: a variable that starts somewhere, a condition that keeps the loop going, and a change to the variable inside the body that eventually makes the condition false.

    Scala details

    • Use var, not val. The counter changes, and a val can't be reassigned. v += 1 on a val does not compile.
    • Scala has no ++. Write count += 1 (or count = count + 1). Writing count++ is a compile error: end of statement expected but identifier found.
    • The condition must be a Boolean. Scala doesn't treat a number as true or false.
    • An unchanged counter never ends. If the body never changes the variable used in the condition, the condition stays true and the loop runs forever.

    The exercise

    The task is to print I promise to learn coding. five times with a loop instead of five separate statements. The lesson builds it in four steps:

    1. Declare the counter: var counter = 1. It starts at 1 and is a var because the loop will change it.
    2. Write the loop header: while (counter <= 5) { }. The body runs for the values 1, 2, 3, 4 and 5.
    3. Print inside the body: println("I promise to learn coding.").
    4. Increase the counter in the body with counter += 1. Without that line, counter stays 1, the condition is always true and the program never stops.
    var counter = 1
    while (counter <= 5) {
        println("I promise to learn coding.")
        counter += 1
    }
    

    After the loop, counter is 6, the first value that fails the condition. Changing the 5 in the condition changes how many lines print; the message appears only once in the code.

    Common mistakes

    • Using < instead of <=. Starting at 1 with counter < 5 gives four passes, not five.
    • Forgetting the update. This is the infinite loop described above.
    • Updating before printing when the printed value matters. In the lesson's exercise the message doesn't use the counter, so the order doesn't matter, but in the next lesson it does.

    Key takeaways

    • while (condition) { ... } repeats the block while the condition is true, checking before each pass.
    • A loop needs a starting value, a condition and an update that moves toward ending it.
    • In Scala the counter is a var and is increased with += 1.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free