Loops...https://play.golang.org/p/gho7Jfq2tai


(Cherolyn Lexvold) #1

https://play.golang.org/p/gho7Jfq2tai

In this code, what does “x%2 != 0” mean?


(Cherolyn Lexvold) #2

I know what != means, more specifically, I don’t know what % means. Is it different than " a fraction of 100"?


(Lutz Horn) #3

This compares the reminder of x when divided by two to zero. It effectively determines if x is odd.

package main

import (
	"fmt"
)

func main() {
	for x := 0; x < 10; x++ {
		isOdd := x%2 != 0
		fmt.Printf("%d is isOdd: %t\n", x, isOdd)
	}
}

Output:

0 is isOdd: false
1 is isOdd: true
2 is isOdd: false
3 is isOdd: true
4 is isOdd: false
5 is isOdd: true
6 is isOdd: false
7 is isOdd: true
8 is isOdd: false
9 is isOdd: true

https://play.golang.com/p/x0Krcox9F6a


(Cherolyn Lexvold) #4

Very cool. Thanks!


(Cherolyn Lexvold) #5

[quote=“lutzhorn, post:3, topic:12384”]
This compares the reminder of x when divided by two to zero. It effectively determines if x is odd.

I saved this answer in a file that I call “Answers to Go Questions”