For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:
Positive numbers are defined as the numbers greater than zero.
Example- 2, 3, 4, 5 etc
For find a number is positive or not we have to check whether the given number is greater than zero. If it is greater than zero then it is a positive number otherwise it will be either zero or negative.
For checking positive numbers from an array, first read the array elements. Traverse the array from the initial position. Check each of the element is greater than zero. If it is greater than zero then it is a positive number.
Here we are showing how to print positive numbers in an array in the Go language. Here variable Arr holds the array elements. Other variables size, i used as the size of the array and index for the loop. Use for loop
to read the array elements.
syntax for for loop
for initializer; condition; incrementor {
}
Find the positive numbers by iterating through another for loop
. If (Arr[i] >= 0) then it is a positive number and print that number.
syntax for if
condition
If condition {
//perform some instruction
}
Given below are the steps which are used in the Go program.
STEP 1: Import the package fmt
STEP 2: Start function main()
STEP 3: Declare the variable size,i
STEP 4: Read the array Arr[] using for loop
STEP 5: Search for the positive numbers in a for loop as if (Arr[i] >=0)
STEP 6: If true it is a positive number otherwise continue the loop
STEP 7:Print the positive numbers using fmt.Println()
package main
import "fmt"
func main() {
var size, i int
fmt.Print("Enter the array size = ")
fmt.Scan(& size)
Arr := make([]int, size)
fmt.Print("Enter the array items = ")
for i = 0; i < size; i++ {
fmt.Scan(& Arr[i])
}
fmt.Print("\nThe Positive Numbers = ")
for i = 0; i < size; i++ {
if Arr[i] >= 0 {
fmt.Print(Arr[i], " ")
}
}
fmt.Println()
}
Enter the array size = 5 Enter the array items = -13 4 -9 0 15 The Positive Numbers = 0 4 15