Start learning free

LESSON 121 OF 414 · WHILE LOOPS & FOR LOOPS

While Loop in Scala: Printing a Range of Numbers

Lesson Read the full explanation

We can achieve many different outcomes with while loops.

For example, we can print all the numbers from 0 through 4:

var i = 0
while(i < 5) {
	println(i)
	i += 1
}

The output of this program is:

0
1
2
3
4

And 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 < 5 true? <=> Is 0 < 5 true? Yes. 
	b. println(i); => Output: 0
	c. i += 1; => i = 1
	
2. Second iteration:
	a. Is i < 5 true? <=> Is 1 < 5 true? Yes. 
	b. println(i); => Output: 1
	c. i += 1; => i = 2
	
3. Third iteration:
	a. Is i < 5 true? <=> Is 2 < 5 true? Yes. 
	b. println(i); => Output: 2
	c. i += 1; => i = 3
	
4. Fourth iteration:
	a. Is i < 5 true? <=> Is 3 < 5 true? Yes. 
	b. println(i); => Output: 3
	c. i += 1; => i = 4
	
5. Fifth iteration:
	a. Is i < 5 true? <=> Is 4 < 5 true? Yes. 
	b. println(i); => Output: 4
	c. i += 1; => i = 5

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

Assignment
Let's print all numbers from 3 to 10 using a while loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    SCALA · WHILE LOOPS & FOR LOOPS

    Printing Numbers in Scala, explained

    Printing numbers with a while loop

    A loop becomes more useful when the body uses the counter. The loop below prints the numbers from 0 through 4:

    var i = 0
    while (i < 5) {
        println(i)
        i += 1
    }
    
    0
    1
    2
    3
    4
    

    The variable i is the counter. It is set before the loop, tested before each pass, used in the body and changed at the end of the body. Here is the run:

    1. i is 0. Is 0 < 5? Yes. Print 0, then i becomes 1.
    2. The same steps repeat for 1, 2, 3 and 4, each printing the current value.
    3. After printing 4, i becomes 5. Is 5 < 5? No, so the loop ends.

    Five passes printed five numbers, 0 to 4, and 5 was never printed because the condition failed before the body could run with it.

    Initialization and condition

    Two choices decide which numbers print:

    • Initialization is the value the counter starts at. It gives the first number printed.
    • Condition decides when to stop. With <, the limit itself is not printed. With <=, it is.

    So i < 5 from 0 gives 0 to 4, while i <= 5 from 0 would give 0 to 5.

    The exercise

    Print all the numbers from 3 to 10, each on its own line. The start value is 3, and 10 must be printed, so the condition uses <=.

    1. Declare the counter as a var, starting at 3: var counter = 3.
    2. Write the loop with the condition counter <= 10. With < the output would stop at 9.
    3. Print the counter with println(counter). println ends each line, so each number is on its own line.
    4. Increase the counter by 1 with counter += 1. If you forget it, the counter stays 3 and the loop never ends.
    var counter = 3
    while (counter <= 10) {
        println(counter)
        counter += 1
    }
    
    3
    4
    5
    6
    7
    8
    9
    10
    

    Other counting patterns

    Changing the update changes the pattern. All three loops below use the same shape: a start value, a condition and an update.

    var counter = 3
    while (counter <= 10) { print(s"$counter "); counter += 1 }
    
    3 4 5 6 7 8 9 10
    
    var even = 2
    while (even <= 10) { print(s"$even "); even += 2 }
    
    2 4 6 8 10
    
    var down = 5
    while (down >= 1) { print(s"$down "); down -= 1 }
    
    5 4 3 2 1
    

    Stepping by 2 changes the update, and counting down changes the start, the condition and the update together. When you write a loop, decide on these three parts first.

    Scala details

    • No ++. Scala has no increment operator; counter++ doesn't compile, with end of statement expected but identifier found. Use counter += 1.
    • Print order matters. The body prints before it increments. Swapping the two lines prints 4 to 11 instead.
    • print keeps the line open. print(s"$counter ") would put the numbers on one line, separated by spaces. println is the one that starts a new line after each value.

    Common mistakes

    • Off by one. The most common error is stopping one number early with < when the last number should be included. Check the first and the last printed numbers against what was asked.
    • Using val for the counter. A val can't be reassigned, so counter += 1 would not compile.
    • Starting at the wrong number. Initializing with 0 or 1 prints extra numbers before 3.

    Key takeaways

    • The initial value of the counter is the first number printed.
    • < excludes the limit and <= includes it.
    • The body must move the counter toward making the condition false.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free