ProgramGuru

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.

Visual explanation for forThe condition controls repeated execution; the update returns to the condition until the loop stops.Initialize i = 1i <= 4?Add i to totalIncrement irepeat while trueWhen the condition becomes false → Print final total
Trace control flow in the order shown, then compare it with the program.

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: 10

Trace 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

In a three-part for loop, when is the condition checked?
Choose one answer. You can try again.

Answer and explanation

Before each iteration

Correct. The loop starts at 1, adds 1, 2, 3 and 4 across four iterations, then stops because 5 does not satisfy i.

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.

    Next lesson: While-Style Loops →