for Loop
Start with Go for Loop
Go uses for for repeated execution. A traditional counted loop has an initializer, a condition and a post statement.
What you’ll learn
- Trace initialization, condition and update.
- Predict the number of iterations.
- Compute a running total using a loop.
Understand the idea
The form for i := 1; i <= 5; i++ { ... } initializes i, checks the condition before each iteration, runs the body when true, and then increments i. When the condition becomes false, control leaves the loop.
Go has no separate while keyword. Variations of for handle conditional loops, infinite loops and iteration over collections.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
total := 0
for i := 1; i <= 4; i++ {
total += i
fmt.Println("After", i, "total is", total)
}
fmt.Println("Final:", total)
}
Output
After 1 total is 1
After 2 total is 3
After 3 total is 6
After 4 total is 10
Final: 10Trace what the program does
The loop starts at 1, adds 1, 2, 3 and 4 across four iterations, then stops because 5 does not satisfy i <= 4. The running total is 1, 3, 6 and finally 10.
Avoid common mistakes
- Be careful with
<versus<=: the boundary changes the number of iterations. i++is a statement in Go, not an expression you can place everywhere.
Try it yourself
Modify the loop to sum the numbers 1 through 5. Predict the total before running.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go for Loop in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.