While-Style Loops
Start with Go While-Style Loops
Go does not have a while keyword. Instead, a for loop with only a condition behaves like a while loop.
What you’ll learn
- Express while-style repetition with for.
- Explain condition checks and stopping.
- Recognize infinite-loop risks.
Understand the idea
Write for count < 3 { ... } when some state changes inside the loop body. The condition is evaluated before every iteration. If it is false from the start, the body never runs.
An infinite loop uses for { ... } and needs a deliberate exit such as break or return when appropriate. Be careful that the loop makes progress toward a stopping condition.
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() {
fuel := 3
for fuel > 0 {
fmt.Println("Fuel units:", fuel)
fuel--
}
fmt.Println("Tank empty")
}
Output
Fuel units: 3
Fuel units: 2
Fuel units: 1
Tank emptyTrace what the program does
The condition is initially true at 3, then the loop prints the current fuel and decreases it. The values printed are 3, 2 and 1. When fuel reaches 0, the condition becomes false and the program exits the loop.
Avoid common mistakes
- If the body never changes a relevant value, a condition-only loop can run forever.
while (fuel > 0)is not Go syntax; usefor fuel > 0.
Try it yourself
Start fuel at 5 and decrease it by 2 on each iteration. Predict which fuel values appear and why the loop ends.
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 While-Style Loops 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.