Go Tutorials

Go Programs

Go Check if Number is Positive, Negative, or Zero


Go Check if Number is Positive, Negative, or Zero

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.


What is Number Sign Checking

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.


Syntax

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"
    }
}


Checking if a number is positive, negative, or zero

We can create a function to check the sign of a given number using conditional statements.

For example,

  1. Define a function named checkNumberSign that takes one parameter n of type int.
  2. Use an if statement to check if the number is greater than zero. If true, return "Positive".
  3. Use an else if statement to check if the number is less than zero. If true, return "Negative".
  4. Use an else statement to handle the case where the number is zero and return "Zero".
  5. In the main function, call the checkNumberSign function with sample numbers and print the results.

Go Program

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)
    }
}

Output

10 is Positive
-5 is Negative
0 is Zero