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
- Loop over the array.
for (num <- nums)reads as "for eachnumtaken fromnums". On every pass,numholds the next element, so the loop needs no index. - Test the element. Inside the loop,
if (num > 0)is true only for positive numbers. Use>and not>=, because zero is not positive. - 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 ofIntvalues. Arrays are created withArray(3, -2, 0, 4, -4), with nonewneeded.- 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. Theforloop is the last expression in the body, and its result isUnit, which matches the declared type.- No
elseneeded. 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 >= 0would 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
printlnafter theifblock, 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.
