go · level 1 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A repeats a block for you.
A loop repeats lines for you. Picture doing star jumps: you count 1, 2, 3, jumping each time. A for loop counts the same way, running its block once for every number.
for i := 1; i <= 3; i++ { has three parts, split by semicolons. Start: make a box i holding 1. Check: keep going while i <= 3. Step: after each round, i++ adds one to i.
Each time round, i holds the current count, so you can use it inside the block.
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("Star jump number", i)
}
fmt.Println("Phew!")
} Programmers often start counting at 0, so for i := 0; i < 3; i++ also runs 3 times.
guess first
Where does the counting start? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println(i)
}
}
your turn
Your turn. Build a times table.
Pick a whole number for the times table, then press run. The loop works out five answers for you.
output
press run to see what happens
fix it
The race is one lap short. Can you fix it?
output
press run to see what happens
- Count the laps in the output. Which number is missing?
- The check
lap < 3stops the loop as soon as lap reaches 3. - Change
<to<=on line 4 so lap 3 counts too, then press run.
nailed it
you made the computer repeat itself. :D
- A
forloop runs its block once per round. - Start, check, step:
i := 1; i <= 3; i++. i++adds one toiafter each round.
new words in your collection
- loop
- for
- ++
This lesson isn’t saved. A free account remembers every lesson you finish.