A loop repeats a block of statements, so you can describe a task once and have it run for every page, every day or every record. Go has one loop keyword, for. Its three-part form starts with an initializer, checks a condition before each pass and runs an update after each pass. A counter declared in the initializer exists only inside the loop.
Read for page := 1; page < 3; page++ as three steps separated by semicolons. page := 1 runs once, before anything else. page < 3 is checked before every pass, and the loop stops as soon as it is false. page++ runs after every pass and adds 1 to page.
Predict and run
Does the loop print 3?
package main
import (
"fmt"
)
func main() {
for page := 1; page < 3; page++ {
fmt.Println(page)
}
}Check your prediction
1
2Change < to <=. Predict the extra line.
Trace the loop by hand
When a loop surprises you, write down each step. For the program above:
pagestarts at 1. Is1 < 3? Yes, so print 1, thenpage++makes it 2.- Is
2 < 3? Yes, so print 2, thenpagebecomes 3. - Is
3 < 3? No, so the loop ends without printing.
The condition is checked before each pass, so a loop whose condition starts false never runs its body at all. Tracing like this is the fastest way to find an off-by-one error, where a loop runs one time too many or one time too few.
Counting in other steps
The update does not have to be ++. Any statement that moves the counter toward the end works: page += 2 visits every other page, and page-- counts down. Make sure the update and the condition agree on the direction, or the condition may never become false.
package main
import (
"fmt"
)
func main() {
for page := 2; page <= 8; page += 2 {
fmt.Println("Page", page)
}
for left := 3; left > 0; left-- {
fmt.Println("Sessions left:", left)
}
}Page 2
Page 4
Page 6
Page 8
Sessions left: 3
Sessions left: 2
Sessions left: 1The first loop stops after 8 because 10 fails page <= 8. The second stops after 1 because 0 fails left > 0, so it never prints Sessions left: 0.
for with only a condition
Leave out the initializer and the update and for keeps just its condition. This is the form other languages call a while loop. Use it when you do not know in advance how many passes you need, only when to stop.
package main
import (
"fmt"
)
func main() {
minutes := 0
sessions := 0
for minutes < 60 {
minutes += 25
sessions++
}
fmt.Println(sessions, "sessions,", minutes, "minutes")
}3 sessions, 75 minutesMake sure the loop can end
If nothing inside the loop changes the values in its condition, the condition never becomes false and the program runs forever. In the editor you would have to stop it. Before running a condition-only loop, point to the line that moves it toward the end.
Leaving early: break and continue
Two statements change the flow inside a loop. continue skips the rest of the current pass and moves on to the next one. break leaves the loop completely. Use them when they make a rule clearer, for example skipping a day off or stopping at the first value that is too large. When a plain condition says the same thing, prefer the condition.
Day 3 is a day off and day 5 is an exam, so studying stops there. Predict which days print.
package main
import (
"fmt"
)
func main() {
for day := 1; day <= 6; day++ {
if day == 3 {
continue
}
if day == 5 {
break
}
fmt.Println("study on day", day)
}
}Check your prediction
study on day 1
study on day 2
study on day 4continue skips the print for day 3 but the loop goes on to day 4. break at day 5 ends the loop, so day 6 never runs.
++ is a statement in Go, not a value. You can write page++ on its own line, but not x := page++, and there is no ++page form.
Practice
Your turn
A book has 100 pages and you read 30 pages a day. You don't know in advance how many days it will take, so use a for loop with only a condition. Print the page you reach each day. The last day ends at page 100, not 120. The output should be:
Day 1: page 30
Day 2: page 60
Day 3: page 90
Day 4: page 100package main
func main() {
// Write your code here.
}Hint 1: the idea
Keep two variables outside the loop: the page you have reached and the day number. The loop runs while the page is below 100. On each pass, move both forward, and if you went past the last page, go back to it.
Hint 2: a first step
Write the loop without the cap first. It should print pages 30, 60, 90 and 120. That last line is the one to fix.
Worked solution
package main
import (
"fmt"
)
func main() {
page := 0
day := 0
for page < 100 {
day++
page += 30
if page > 100 {
page = 100
}
fmt.Printf("Day %d: page %d\n", day, page)
}
}Day 1: page 30
Day 2: page 60
Day 3: page 90
Day 4: page 100The line that makes the loop end is page += 30. Without it page would stay at 0 and the loop would run forever.
Completion is saved in this browser only. It does not measure mastery.