Start learning free

LESSON 130 OF 414 · LOOPS & CONDITIONALS

Print Positive Numbers From an Array in Scala: for and if

Practice Read the full explanation

Given an array of integers, print to the console the positive numbers, one on each line.

A number n is positive if it is strictly greater than 0.

Example:

Input: nums = [3, -2, 0, 4, -4]
Output (console):
3
4

Note:

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


STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · LOOPS & CONDITIONALS

    Print Positive Numbers From Array in Scala, explained

    Problem overview

    The method printPositiveNumbers(nums: Array[Int]): Unit receives an array of integers and prints the positive ones, each on its own line. A number is positive when it is strictly greater than 0, so zero is not printed. The method returns nothing: the console output is the result.

    In the example, nums is Array(3, -2, 0, 4, -4). The 3 and the 4 are positive, and -2, 0 and -4 are not, so the output is:

    3
    4
    

    Approach: visit every element and filter with a condition

    The task combines two basic tools. A loop visits each element of the array once, and an if decides for each element whether to act on it. The order of the output is the order of the array, because the loop goes from the first element to the last.

    Nothing needs to be remembered between elements, so the loop needs no counter or accumulator. Each element is judged on its own.

    Step by step

    1. Loop over the array. for (num <- nums) reads as "for each num taken from nums". On every pass, num holds the next element, so the loop needs no index.
    2. Test the element. Inside the loop, if (num > 0) is true only for positive numbers. Use > and not >=, because zero is not positive.
    3. Print it. Inside the if, println(num) writes the number followed by a line break.

    The solution in Scala

    class Solution {
        def printPositiveNumbers(nums: Array[Int]): Unit = {
            for (num <- nums) {
                if (num > 0) {
                    println(num)
                }
            }
        }
    }
    

    The Scala details worth a closer look:

    • Array[Int]. Scala writes type parameters in square brackets, so this is an array of Int values. Arrays are created with Array(3, -2, 0, 4, -4), with no new needed.
    • The generator num <- nums. The same syntax works for ranges, lists and other collections. The loop variable is a new value on each pass and can't be reassigned.
    • Unit. The return type for a method that is called for its effect. The for loop is the last expression in the body, and its result is Unit, which matches the declared type.
    • No else needed. When the condition is false, nothing happens, and the loop moves to the next element.

    Complexity

    Time: O(n) for an array of n elements. Each element is visited once, and the comparison and the print each take constant time.

    Space: O(1). The method creates no new collection. It only holds the current element.

    Edge cases and common mistakes

    • Empty array. The loop body never runs, so nothing is printed. That is the correct output.
    • No positive numbers. Array(-1, 0, -5) also prints nothing.
    • Zero. num >= 0 would print the 0 in the example, which is wrong.
    • Returning instead of printing. The method must write to the console. Its return type is Unit, so there is no value to hand back.
    • Duplicates. They are printed as many times as they appear: Array(2, 2, -1) prints 2 twice.
    • Printing too much. Putting println after the if block, not inside it, prints every element.

    Testing

    • Array(3, -2, 0, 4, -4) prints 3 and 4.
    • Array(1, 2, 3) prints 1, 2 and 3.
    • Array(-7, 0) prints nothing.
    • Array() 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