Count with a three-part for loop
Count with a three-part for loop
A for loop repeats a block. In for i := 0; i < 3; i++ { ... }, the initializer runs once, the condition is checked before each iteration, and the post statement runs after each completed iteration. Use this form when the counting rule is known.
package main
import "fmt"
func main() { for i := 0; i < 3; i++ { fmt.Println(i) }}The values printed are 0, 1 and 2. At 3 the condition becomes false, so the body does not run. The variable i declared in the initializer is local to the loop.
Count backward
package main
import "fmt"
func main() { for seconds := 3; seconds > 0; seconds-- { fmt.Println(seconds) } fmt.Println("go!")}Use a decreasing post statement with a decreasing target. A common off-by-one mistake is using <= 3 when you intend only three iterations starting at zero; that would run four times. Check the first and last values before running.
Try it locally
Print the even numbers 2, 4, 6, 8 using one three-part loop. Change the step rather than using an if statement.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Loops 01: Count with a three-part for loop
Check the lesson objective before moving on.
How many times does for i := 0; i < 3; i++ run?
When is the post statement executed in a normal iteration?