Start learning free

LESSON 132 OF 414 · LOOPS & CONDITIONALS

Print Even Odd in Scala: for Loop and Modulo

Practice Read the full explanation

Given a positive integer n, for each number from 0 to n - 1, print "odd" if the number is odd or the number itself if it is even.

Example:

Input: n = 6
Output (console):
0
odd
2
odd
4
odd


Note:

You have to print to the console, your function shouldn't return anything.

STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · LOOPS & CONDITIONALS

    Print Even Odd in Scala, explained

    Problem overview

    The method printEvenOdd takes an Int named n and prints one line for each number from 0 to n - 1. If the number is odd, the line is the word odd. If it is even, the line is the number itself. The method returns Unit, Scala's "nothing useful" result, so it only prints and gives nothing back.

    For n = 6 the output is:

    0
    odd
    2
    odd
    4
    odd
    

    Zero is even, so the first line is 0. The last number visited is 5, which is odd, so the last line is odd. The number 6 itself is never printed.

    Approach

    The task has two parts: visit every number in a range, and choose what to print for each one. A for loop does the first part, and an if / else does the second. The test for "odd" is the remainder after dividing by 2, which Scala writes with the % operator. A number divided by 2 leaves a remainder of 1 when it is odd and 0 when it is even.

    Step by step

    1. Loop over the range. for (i <- 0 until n) runs the body once for each value of i, starting at 0. The part i <- 0 until n is called a generator. until excludes its upper end, so n itself is not visited, which is exactly what "from 0 to n - 1" asks for. Writing 0 to n instead would include n.
    2. Test for odd. Inside the loop, i % 2 == 1 is true when i is odd. In that case the method prints the string "odd" with println.
    3. Print the number otherwise. In the else branch, println(i) prints the number. Because the two branches are exclusive, each number produces exactly one line.

    The solution in Scala

    class Solution {
        def printEvenOdd(n: Int): Unit = {
            for (i <- 0 until n) {
                if (i % 2 == 1) {
                    println("odd")
                } else {
                    println(i)
                }
            }
        }
    }
    

    Some Scala details in these few lines:

    • i is a val. The loop variable is created fresh for every pass and can't be reassigned inside the body. Its type, Int, is inferred from the range.
    • 0 until n is a range, not a list. It does not store the numbers; it produces them as the loop asks for them. 0 until 0 is an empty range, so printEvenOdd(0) prints nothing.
    • println takes anything. It accepts both a String and an Int and ends each output with a line break, so the two branches can print different types.
    • if / else is an expression in Scala. Here it is used as a statement, because both branches only print and nothing uses the value.
    • No return. The method has the result type Unit, so there is nothing to return.

    Edge cases and common mistakes

    • n = 0. The range is empty and nothing is printed.
    • n = 1. Only the number 0 is visited, so the output is a single line, 0.
    • Using to instead of until. 0 to n includes n, so for n = 6 the output would gain an extra line, 6.
    • Testing for even instead of odd. i % 2 == 0 is just as valid, as long as the branches are swapped so that evens still print the number.
    • Printing the wrong thing in the odd case. The lines must be the word odd in lowercase, with no quotes in the output. "odd" in the code is a string literal, so the quotes are not printed.
    • Returning instead of printing. The method has to write to the console, not build and return a value.

    Testing

    • printEvenOdd(6) prints 0, odd, 2, odd, 4, odd, one per line.
    • printEvenOdd(1) prints 0.
    • printEvenOdd(0) prints nothing.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free