In this tutorial, we will learn how to check if a number is positive, negative, or zero in Go. We will cover the basic conditional statements to determine the sign of a number.
Number sign checking is the process of determining whether a number is positive, negative, or zero. This is commonly done using conditional statements to compare the number to zero.
The syntax to check if a number is positive, negative, or zero in Go is:
func checkNumberSign(n int) string {
if n > 0 {
return "Positive"
} else if n < 0 {
return "Negative"
} else {
return "Zero"
}
}
We can create a function to check the sign of a given number using conditional statements.
For example,
checkNumberSign
that takes one parameter n
of type int
.if
statement to check if the number is greater than zero. If true, return "Positive".else if
statement to check if the number is less than zero. If true, return "Negative".else
statement to handle the case where the number is zero and return "Zero".checkNumberSign
function with sample numbers and print the results.package main
import (
"fmt"
)
func checkNumberSign(n int) string {
if n > 0 {
return "Positive"
} else if n < 0 {
return "Negative"
} else {
return "Zero"
}
}
func main() {
// Sample numbers
numbers := []int{10, -5, 0}
// Check and print the sign of each number
for _, number := range numbers {
result := checkNumberSign(number)
fmt.Printf("%d is %s\n", number, result)
}
}
10 is Positive -5 is Negative 0 is Zero