Even or odd in Go

Read an integer and print whether it is even or odd using the modulo operator, then check your logic against a complete tested Go solution.

Level
Easy
Estimated time
12 min
Concepts covered
conditions, modulo

A number is even when it can be divided by two with no remainder, and odd otherwise. This exercise puts the modulo operator % and an if/else statement to work.

Statement

Given an integer stored in a variable, print even if it is a multiple of two and odd if it is not.

Constraints:

  • Decide with the remainder operator %, not with division.
  • Print exactly even or odd, in lower case, followed by a newline.
  • Your logic must be correct for 0 (which is even) and for negative numbers.

Example

number = 7   ->  odd
number = 10  ->  even
number = 0   ->  even

Starter code

package main

import "fmt"

func main() {
	number := 7
	// Print "even" or "odd" depending on number.
}

Hints

Hint 1

The expression number % 2 gives the remainder of the division by two. It is 0 for an even number.

Hint 2

Compare that remainder to zero with ==, not with a single =, which is assignment.

Hint 3

Use if number%2 == 0 { ... } else { ... } and print the right word in each branch.

Solution

Show the solution
package main

import "fmt"

func main() {
	number := 7

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

The operator % returns the remainder of an integer division. When number % 2 equals 0, the number divides cleanly by two and is even; any other remainder means it is odd. Because 0 % 2 is 0, zero is correctly reported as even, and Go’s remainder rules keep the check correct for negative values too.

Common mistakes:

  • Using / (division) instead of % (remainder). Division discards the part you actually need.
  • Writing if number%2 = 0. A comparison uses ==; a single = assigns and will not compile.
  • Printing Even or ODD. The expected output is lower case.

To go deeper into branching, read Conditionals in Go.

Search

Search runs entirely in your browser.