golang example to check number/integer even or odd

In this blog post, we will learn about two programs in golang.

The first program is how to check input number is even or odd. the second program is how to check a given array or slice of numbers for even or odd numbers.

The logic for any number is even or odd is as follows.

Even number is a number divisible to 2 is zero. if operation modulus operator divisible by 2 with remainder=0.

How to check number is even or odd in Golang

In the below program. Scanlin function is used to take the input number from the user console ie command line. user entered a number is stored in the number variable

Now checking number is even or odd, we used modulus operator % and check remainder is zero with divisible by 2. Following go language features are used for this program.

if the number is divisible by 2, then it is an even number, an else odd number

package main

import (
    "fmt"
)

func main() {
    fmt.Print("Please enter first number: ")
    var number int
    fmt.Scanln( & number) // take input from user
    if number % 2 == 0 {
        fmt.Printf("%v is a Even Number", number)
    } else {
        fmt.Printf("%v is a Odd Number", number)
    }
}

When you compile and run the program, the output will be:

Please enter first number: 23
23 is a Odd Number
Please enter first number: 54
54 is a Even Number

Golang Program Example to check array or slices of Number are even or odd?

The first array/slice creates with initialized values.

You can learn more about slice

Each number is checked for an odd or even number and printed the result to the console.

package main

import (
    "fmt"
)

func main() {
    var numbs = [] int {
        51, 4, 5, 6, 24, 11
    }
    for _, number: = range numbs {
        if number % 2 == 0 {
            fmt.Printf("%v is a Even Number\n", number)
        } else {
            fmt.Printf("%v is a Odd Number\n", number)
        }
    }
}

The output of the above program is

51 is a Odd Number
4 is a Even Number
5 is a Odd Number
6 is a Even Number
24 is a Even Number
11 is a Odd Number

Conclusion

learned following two programs to check number is odd or even in golang.

  • given input number
  • Array of number/slice