go · level 1 · unit 5 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Put an if inside a loop to decide every round.
An if can live inside a loop, so the program decides something on every round. Picture walking down a street and knocking only on the red doors.
% gives the remainder. A number is when n%2 == 0, because it splits between two with nothing left over. Otherwise it is .
To count matches, make a box holding 0 before the loop. Inside, each time the if is true, add 1. After the loop, the box holds the total.
package main
import "fmt"
func main() {
evens := 0
for n := 1; n <= 6; n++ {
if n%2 == 0 {
fmt.Println(n, "is even")
evens = evens + 1
}
}
fmt.Println("Even numbers:", evens)
} Make the counting box before the loop starts, and show it after the loop ends.
guess first
Clap on the even numbers. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
for n := 1; n <= 5; n++ {
if n%2 == 0 {
fmt.Println("clap")
} else {
fmt.Println(n)
}
}
}
your turn
Your turn. Hunt for multiples of 3.
Choose how high to count with a whole number. The loop counts how many numbers on the way divide exactly by 3.
output
press run to see what happens
fix it
These should be the even numbers. Fix it!
output
press run to see what happens
- The output shows 1, 3 and 5. Are those even?
- Even numbers leave nothing over when split in two, so their remainder is 0, not 1.
- Change
n%2 == 1ton%2 == 0on line 5, then press run.
nailed it
your loops can make decisions. :D
- An
ifinside a loop decides something every round. - A number is even when
n%2 == 0. - Count matches in a box that starts at 0.
new words in your collection
- even
- odd
This lesson isn’t saved. A free account remembers every lesson you finish.