This Go program to Print Positive Numbers in an Array uses for loop to iterate user-entered array items. Within the for loop (for i = 0; i < posize; i++), the if condition (if posArr[i] >= 0) checks whether the number is greater than or equal to zero. If True, it is a Positive number, so print it.
package main import "fmt" func main() { var posize, i int fmt.Print("Enter the Positive Array Size = ") fmt.Scan(&posize) posArr := make([]int, posize) fmt.Print("Enter the Positive Array Items = ") for i = 0; i < posize; i++ { fmt.Scan(&posArr[i]) } fmt.Print("\nThe Positive Numbers in this posArra = ") for i = 0; i < posize; i++ { if posArr[i] >= 0 { fmt.Print(posArr[i], " ") } } fmt.Println() }
Enter the Positive Array Size = 5
Enter the Positive Array Items = -22 0 -9 14 11
The Positive Numbers in this posArra = 0 14 11
Go Program to Print Positive Numbers in an Array using For Loop Range
package main import "fmt" func main() { var posize int fmt.Print("Enter the Positive Array Size = ") fmt.Scan(&posize) posArr := make([]int, posize) fmt.Print("Enter the Positive Array Items = ") for i := 0; i < posize; i++ { fmt.Scan(&posArr[i]) } fmt.Print("\nThe Positive Numbers in this posArra = ") for _, po := range posArr { if po >= 0 { fmt.Print(po, " ") } } fmt.Println() }
In this Golang program, we created a (printPositveNum(posArr []int)) function to print Positive array numbers.
package main import "fmt" func printPositveNum(posArr []int) { fmt.Print("\nThe Positive Numbers in this posArra = ") for _, po := range posArr { if po >= 0 { fmt.Print(po, " ") } } } func main() { var posize int fmt.Print("Enter the Positive Array Size = ") fmt.Scan(&posize) posArr := make([]int, posize) fmt.Print("Enter the Positive Array Items = ") for i := 0; i < posize; i++ { fmt.Scan(&posArr[i]) } printPositveNum(posArr) fmt.Println() }
Enter the Positive Array Size = 10
Enter the Positive Array Items = 1 0 -99 8 -66 -55 2 125 -67 220
The Positive Numbers in this posArra = 1 0 8 2 125 220