3.2 Repeat Code with Go's Three For Loops

3.2 Repeat Code with Go's Three For Loops

TL;DR

  • A for loop runs a block of code over and over again.
  • The traditional loop is for when you know the exact number of repetitions, like counting to ten.
  • The conditional loop is for when you need to repeat until something changes, like waiting for a download to finish.
  • The infinite loop runs forever until you manually stop it, perfect for programs that should always be running, like a web server.

Why This Matters

So much of programming is about automation. You don't want to write the same line of code 100 times to process 100 emails. You want to write it once and tell the computer, "Do this 100 times." Loops are the fundamental tool for that. Master them, and you can process lists of data, build simple animations, or check for new messages every few seconds.


Concepts in Plain English

Before we dive in, let's get a few key ideas straight. Think of it like baking cookies.

  • Loop: The entire recipe for making a batch of cookies, which you might repeat.
  • Iteration: Placing one tray of cookies in the oven. It's a single cycle of the recipe.
  • Condition: The check you perform. "Is the kitchen timer done?" If not, you keep waiting (the loop continues). If yes, you stop.

Here's a quick glossary to keep handy.

TermSimple DefinitionWhere It Shows Up
forThe only keyword Go uses to start a loop.At the beginning of every loop.
IterationA single run-through of the code inside the loop.Every time the loop repeats.
ConditionA true/false question that decides if the loop runs again.Inside the for statement.
StatementA piece of the for loop's setup, like the starting counter.In the traditional for loop.

Do It Step by Step

You don't need to install anything to try these examples! You can run them all right in your browser using the Go Playground.


1. The Traditional Loop (The Counter)

Use this when you know exactly how many times you want the loop to run. It has three parts separated by semicolons: a start, a condition, and an update.

It's like a workout routine. "Do 10 push-ups." You have a start (1), an end condition (stop when you hit 10), and an update (count up by one after each push-up).

Here's how its three parts work:

PartWhat It DoesExample
initCreates a counter variable that only exists for this loop.i := 0 (Start i at 0)
conditionA check that runs before each iteration. If it's true, the loop runs.i < 3 (Keep going as long as i is less than 3)
postRuns after each iteration, usually to update the counter.i++ (Add one to i)

Let's see it in action.

  1. Goal: Print a numbered message three times.

Expected Output:

This is message number 0
This is message number 1
This is message number 2

Code:

package main

import "fmt"

func main() {
    // This loop will run 3 times: for i=0, i=1, and i=2.
    for i := 0; i < 3; i++ {
        // The code inside these curly braces {} is what repeats.
        fmt.Println("This is message number", i)
    }
}
Pro Tip — Programmers love to start counting from 0. It often makes the math simpler!

2. The Conditional Loop (The Watcher)

Use this when you don't know how many iterations you need, but you know the condition that should stop it. It's like a traditional loop but with only the condition part.

It's like waiting for water to boil. You don't know if it will take 3 minutes or 5 minutes. You just keep checking ("Is it boiling yet?"). The loop runs while the condition is true.

  1. Goal: Keep a program "running" as long as a variable isWorking is true.

Expected Output:

Still working...
Still working...
Work is done!

Code:

package main

import "fmt"

func main() {
    // We'll pretend the program is working initially.
    isWorking := true
    runCount := 0

    // This loop runs as long as isWorking is true.
    for isWorking {
        fmt.Println("Still working...")
        runCount++ // Add one to our counter

        // Let's create a rule to stop the loop.
        if runCount == 2 {
            isWorking = false // This will make the loop condition false.
        }
    }

    fmt.Println("Work is done!")
}
Note — Other languages have a while keyword for this. Go simplifies things by just using for.

3. The Infinite Loop (The Forever Loop)

Use this for tasks that should run continuously until the entire program is shut down.

It’s like the Earth spinning. It just keeps going with no built-in end condition. It only stops if something external (like a giant asteroid) happens.

  1. Goal: Print a message every second, forever.
  2. Expected Output: The program will print the message over and over, once per second, until you manually stop it. In a terminal, you'd press Ctrl+C.

Code:

package main

import (
    "fmt"
    "time"
)

func main() {
    // A 'for' with no conditions runs forever.
    for {
        fmt.Println("Server is listening for connections...")
        // We'll pause for one second so we don't crash the playground.
        time.Sleep(1 * time.Second)
    }
}
Warning — Be careful with infinite loops! Without a pause (time.Sleep) or a way to break out of them, they can easily consume all your computer's processing power.

Examples Section

Let's put it all together.

Example A: Minimal Countdown

This is a classic traditional for loop that counts backward. Notice the three parts: start at 3, continue as long as i > 0, and subtract one (i--) each time.

package main

import "fmt"

func main() {
    fmt.Println("Starting countdown!")
    for i := 3; i > 0; i-- {
        fmt.Println(i)
    }
    fmt.Println("Liftoff!")
}

Example B: Simple "Guess the Number"

This example uses a conditional loop. It keeps asking for a guess until the correct number is entered. We don't know how many tries it will take.

package main

import "fmt"

func main() {
    magicNumber := 7
    guess := 0

    // Loop as long as the guess is NOT the magic number.
    for guess != magicNumber {
        fmt.Println("Guess the number:")
        // In a real app, we'd get input from the user.
        // Here, we'll just pretend they guess a few times.
        if guess == 0 {
            guess = 3 // First wrong guess
            fmt.Println("You guessed 3... Nope!")
        } else {
            guess = 7 // Second, correct guess
            fmt.Println("You guessed 7... You got it!")
        }
    }
}

This flow of choosing the right loop can be visualized like this:

graph LR
  A[Start] --> B{Know the exact number of repeats?}
  B -->|Yes| C[Traditional loop - for i from 0 to 9]
  B -->|No| D[Need to repeat until a condition is met?]
  D -->|Yes| E[Conditional loop - while not isReady]
  D -->|No| F[Infinite loop - endless loop]

ASCII Fallback: Start -> Do you know the exact number of repeats? If yes, use a Traditional Loop. If no, ask: Need to repeat until a condition is met? If yes, use a Conditional Loop. If no, use an Infinite Loop.


Common Pitfalls

  • Off-by-One Errors: Mixing up < (less than) and <= (less than or equal to) is a classic mistake. for i := 0; i < 5; i++ runs 5 times (for 0, 1, 2, 3, 4). for i := 0; i <= 5; i++ runs 6 times.
  • Accidental Infinite Loops: If the condition in a conditional loop can never become false, it will run forever. Always make sure something inside the loop can eventually stop it.
  • Forgetting to Update: In a traditional loop, if you forget the i++ part, i will stay 0 forever, and the loop will never end.

FAQ

1. Does Go have a while or do-while loop like other languages?

Nope! Go keeps it simple. The conditional for (for condition {}) is Go's version of a while loop.

2. What do i++ and i– mean?

They are just convenient shortcuts. i++ means "add one to i" (i = i + 1), and i-- means "subtract one from i" (i = i - 1).

3. How do I stop a loop early?

You can use the break keyword. If the code hits a break, it immediately jumps out of the loop and continues with the code that comes after it.

4. Can I have a loop inside another loop?

Absolutely! This is called a "nested loop" and is very common for working with grids or tables of data, like an Excel spreadsheet.


Recap

You've just learned a core concept in programming. Great job!

  • Go uses a single keyword, for, for every kind of loop.
  • When you need to count a specific number of times, use the traditional for loop with its three parts (for i := 0; i < N; i++).
  • When you need to watch for a condition to change, use the conditional for loop (for someCondition).
  • When you need a program to run forever, like a server, use the infinite for loop (for {}).

Start by getting comfortable with the traditional loop. It's the one you'll probably use most often. Happy coding!