Tuesday, December 18, 2018

Golang Example - Check if a number/integer is positive or negative

In this Example, you will learn programs to check number is positive or negative, First is using if else statement. Second is using standard library Math Signbit function.

Positive number are whole number which are greater than zero ie 1,2,3...
Negative numbers are number which are lesser than zero , -1,-2
Each positive number  has a corresponding negative number

To understanding the below programs, You have following features understanding in Go Language.

Golang Example - Check if Number is positive or negative using if else statement

The below program read number from an user console, store it in variable number.
Here are steps to check positive or negative number using if else statements
  • if  number is greater than zero, Number is positive
  • if number is less than zero , Number is negative
  • else, number=0 is executed, zero value printed to console
Here is a example program to check positive or negative number
package main
import (
 "fmt"
)

func main() {
 var number int
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 if number < 0 {
  fmt.Printf(" %d is a negative integer.", number)
 } else if number > 0 {
  fmt.Printf("%d  is a positive integer.", number)
 } else {
  fmt.Printf("%d is Zero.", number)
 }
}
output is
Enter Number:4
4  is a positive integer.

Enter Number:-9
 -9 is a negative integer.

Enter Number:0
0 is Zero.

Example Program to check Positive or negative number using standard library functions

The below program uses Math Signbit function. Signbit function return true, if number is negative, return false for positive number.
package main
import (
 "fmt"
 "math"
)

func main() {
 var number float64
 fmt.Print("Enter Number:")
 fmt.Scanln(&number)
 isPositive := math.Signbit(number)
 if isPositive {
  fmt.Printf("%f  is a negative integer.", number)

 } else {
  fmt.Printf(" %f is a positive integer.", number)

 }
}
Output is
Enter Number:25
25.000000 is a positive integer.

Enter Number:-24
-24.000000  is a negative integer.

Related article


EmoticonEmoticon