Go Program to Print Negative Numbers in an Array

Write a Go program to Print Negative Numbers in an Array using For loop. Here, we used for loop (for i = 0; i < ngsize; i++) to iterate user-entered array items. Within the loop, the if condition (if negArr[i] < 0) checks whether the number is less than zero. If True, it is a negative number, so print it.

package main

import "fmt"

func main() {
    var ngsize, i int

    fmt.Print("Enter the Negative Array Size = ")
    fmt.Scan(&ngsize)

    negArr := make([]int, ngsize)

    fmt.Print("Enter the Negative Array Items  = ")
    for i = 0; i < ngsize; i++ {
        fmt.Scan(&negArr[i])
    }

    fmt.Print("\nThe Negative Numbers in this negArr = ")
    for i = 0; i < ngsize; i++ {
        if negArr[i] < 0 {
            fmt.Print(negArr[i], " ")
        }
    }
    fmt.Println()
}
Enter the Negative Array Size = 5
Enter the Negative Array Items  = 22 -9 11 -8 -15

The Negative Numbers in this negArr = -9 -8 -15 

Go Program to Print Negative Numbers in an Array using For Loop Range

package main

import "fmt"

func main() {
    var ngsize, i int

    fmt.Print("Enter the Negative Array Size = ")
    fmt.Scan(&ngsize)

    negArr := make([]int, ngsize)

    fmt.Print("Enter the Negative Array Items  = ")
    for i = 0; i < ngsize; i++ {
        fmt.Scan(&negArr[i])
    }

    fmt.Print("\nThe Negative Numbers in this negArr = ")
    for _, ng := range negArr {
        if ng < 0 {
            fmt.Print(ng, " ")
        }
    }
    fmt.Println()
}
Enter the Negative Array Size = 7
Enter the Negative Array Items  = 0 22 -90 -11 3 -2 2

The Negative Numbers in this negArr = -90 -11 -2 

In this Golang program, we created a function (printNegativeNum(negArr []int)) to print negative numbers in a given array.

package main

import "fmt"

func printNegativeNum(negArr []int) {
    fmt.Print("\nThe Negative Numbers in this negArr = ")
    for _, ng := range negArr {
        if ng < 0 {
            fmt.Print(ng, " ")
        }
    }
}

func main() {
    var ngsize, i int

    fmt.Print("Enter the Negative Array Size = ")
    fmt.Scan(&ngsize)

    negArr := make([]int, ngsize)

    fmt.Print("Enter the Negative Array Items  = ")
    for i = 0; i < ngsize; i++ {
        fmt.Scan(&negArr[i])
    }
    printNegativeNum(negArr)

    fmt.Println()
}
Enter the Negative Array Size = 5
Enter the Negative Array Items  = 11 -99 -66 0 -33

The Negative Numbers in this negArr = -99 -66 -33