I'm going through some golang tutorials, and I came across this for
loop:
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
I'm confused by the n%2
statement.
The output of this is:
1
3
5
It looks like these are not multiples of 2, but I'm not understanding the == 0
part of the statement if that's the case? Is there a resource that talks about this operation, or something I should look up?
This is called a modulus operator, it returns the remainder of a division operation. Hence == 0 will be true when X can be evenly divided by Y.
This operator and % to represent it is common in many languages.
See related question: Understanding The Modulus Operator %
It's the remainder/modulo-operator. This returns the rest of the division with the given number: https://en.wikipedia.org/wiki/Modulo_operation
This code fragment calculates all uneven numbers.