Go Program to Check Whether a Number is Even or Odd

In this post, we will learn how to write a program to check whether a number is even or odd using the Go programming language.

Any number that is completely divisible by 2 is called an even number, whereas the number that leaves a remainder when divided by 2 is called an odd number.

The below program asks the user to enter a positive integer, then uses the if… else condition to check whether the entered integer is exactly divisible by 2 or not.

If the condition is true, then the entered integer is an even number; otherwise, it is an odd number.

So, without further ado, let’s begin this tutorial.

Go Program to Check Whether a Number is Even or Odd

// Go Program to Check Whether a Number is Even or Odd
package main

import (
	"fmt"
)

func main() {
	var num int

	fmt.Print("Enter an integer: ")
	fmt.Scanln(&num)

	if num%2 == 0 {
		fmt.Println(num, " is an even number.")
	} else {
		fmt.Println(num, "is an odd number.")
	}
}

Output

Enter an integer: 31
31 is an odd number.

How Does This Program Work?

	var num int

We have declared an integer data type variable named num.

	fmt.Print("Enter an integer: ")
	fmt.Scanln(&num)

The user is asked to enter a positive integer to find out whether it’s an even number or an odd number. The integer entered by the user is stored in num named variable.

	if num%2 == 0 {
		fmt.Println(num, " is an even number.")
	} else {
		fmt.Println(num, "is an odd number.")
	}

Now, we take advantage of the if…else condition to check whether the integer is an even number or an odd number.

We use the % modulus operator to find the remainder when num is divided by 2. If the remainder is 0, then it means the integer is completely divisible by 2. Therefore, the integer is an even number.

If the above condition is false, then it means that the integer leaves a remainder other than 0. Therefore, in such a case, the entered integer will be an odd number.

Conclusion

In this post, you learned how to write a program to check whether a number is even or odd using the Go programming language.

If you have any doubts regarding the tutorial, leave your queries in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *