Start learning free

LESSON 125 OF 338 · LOOPS & CONDITIONALS

Print Positive Numbers From Array in Go: range 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

    GO · LOOPS & CONDITIONALS

    Print Positive Numbers From Array in Go, explained

    Problem overview

    The function printPositiveNumbers receives a slice of integers, nums. It prints every positive number in it, one per line, and returns nothing. A number is positive only when it is strictly greater than 0, so zero doesn't count.

    For nums = []int{3, -2, 0, 4, -4} the output is 3 and then 4. The -2 and -4 are negative and the 0 is neither positive nor negative, so none of them appears. The numbers are printed in the order they have in the slice.

    Approach: visit each element and test it

    Nothing needs to be stored or computed across elements. Each number is judged on its own, so the plan is to look at the elements one at a time, in order, and print the ones that pass the test. In Go that means a for ... range loop for the visiting and an if for the test.

    Step by step

    1. Loop over the slice with range. On every pass, range hands back two values: the index and the element. The index is not needed here, and Go does not allow a declared variable to go unused, so it is discarded with the blank identifier _. The element is named num.
    2. Check the sign. An if with num > 0 accepts only positive numbers. The comparison is strict, so 0 is rejected.
    3. Print the number with fmt.Println inside the if. It adds a newline after the value, so every number gets its own line.

    The solution in Go

    func printPositiveNumbers(nums []int) {
        for _, num := range nums {
            if num > 0 {
                fmt.Println(num)
            }
        }
    }
    

    The Go details:

    • range gives two values for a slice. The first is the index and the second is a copy of the element. With a single variable, for i := range nums gives only the indices, which is a common surprise.
    • The blank identifier _. It receives a value and throws it away, so it never counts as an unused variable.
    • Slices instead of arrays. The parameter type []int is a slice, a view of a sequence of integers whose length can vary. Its length is len(nums), though the loop doesn't need it. An empty or nil slice simply makes the loop run zero times.
    • No parentheses around the condition, but braces are always required.
    • No return value. The function prints, so its signature stops after the parameter list.

    Complexity

    Time: O(n), where n is the number of elements, because each element is visited once and tested in constant time.

    Space: O(1). The function keeps nothing beyond the loop's variables. The slice is not copied, and the elements are printed as they are found.

    Edge cases and common mistakes

    • Zero. Using num >= 0 would print 0 for the example input, which is wrong.
    • An empty slice. Nothing is printed, and nothing goes wrong.
    • All negative numbers. Again nothing is printed.
    • Printing the index. Writing for i, num := range nums and printing i outputs positions, not values. If num is then left unused, the program doesn't compile.
    • Returning instead of printing. The function is expected to write to the console, not to hand back a slice of positives.
    • Duplicates. Every positive element is printed, including repeats: []int{2, 2} prints 2 twice.

    Testing

    • []int{3, -2, 0, 4, -4} prints 3 and 4.
    • []int{-1, -5} prints nothing.
    • []int{0} prints nothing.
    • []int{1, 2, 3} prints 1, 2 and 3.
    • []int{} prints nothing.
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free