Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 08 Beginner

Loops in Go

Updated: May 17, 2026
5 min read

# CHAPTER 8

Loops in Go

1. Introduction

Imagine you need to insert 5,000 user records into a database. Writing the insert command 5,000 times manually is impossible. Loops solve this by allowing a block of code to execute repeatedly as long as a condition is true.

In C, Java, and Python, you have for, while, and do-while loops. Go has only one looping keyword: for. The Go creators designed for to be so flexible that it can replicate all the others, keeping the language simple.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use the standard for loop (Initialization, Condition, Post).
  • Use the for loop as a while loop.
  • Create Infinite loops.
  • Manipulate execution flow using break and continue.
  • Understand the basics of the range keyword.

3. The Standard for Loop

Used when you know exactly how many times you want the loop to run.

Syntax: for initialization; condition; post { // code }

go
123456789
package main
import "fmt"

func main() {
    // Prints numbers 1 to 5
    for i := 1; i <= 5; i++ {
        fmt.Printf("Count: %d\n", i)
    }
}

How it works:

  1. 1. i := 1 (Initialization): Executes ONCE at the start.
  1. 2. i <= 5 (Condition): Checked before every loop. If true, run the code. If false, stop.
  1. 3. i++ (Post): Executes *after* the code block runs, then goes back to step 2.

4. The "While" Loop (Using for)

If you drop the Initialization and Post statements, the for loop behaves exactly like a traditional while loop. Used when you don't know the exact number of iterations, but you know the stopping condition.
go
123456789
func main() {
    count := 1

    // This is Go's version of a "while" loop
    for count <= 3 {
        fmt.Println("Hello!")
        count++ // CRITICAL: Don't forget to update the condition!
    }
}

5. The Infinite Loop

If you drop all three components, the loop will run forever. This is heavily used in backend web servers that must run 24/7 to listen for incoming requests.
go
123456
func main() {
    for {
        fmt.Println("I will run forever until you press Ctrl+C!")
        // In a real app, this might be: ListenForNetworkConnections()
    }
}

6. Flow Control: break and continue

  • break: Immediately stops and destroys the loop completely.
  • continue: Skips the rest of the *current* iteration and instantly jumps back to the top for the next iteration.
go
123456789101112
func main() {
    for i := 1; i <= 10; i++ {
        if i == 4 {
            continue // Skips printing 4
        }
        if i == 8 {
            break // Stops the loop entirely at 8
        }
        fmt.Print(i, " ")
    }
    // Output: 1 2 3 5 6 7
}

7. The range Keyword (Preview)

We will cover Arrays and Maps later, but the most common way to loop over collections of data in Go is using the for ... range syntax.
go
12345678
func main() {
    names := []string{"Alice", "Bob", "Charlie"}

    // range automatically provides the Index and the Value
    for index, name := range names {
        fmt.Printf("Index: %d, Name: %s\n", index, name)
    }
}

8. Mini Project: Multiplication Table Generator

Let's build a program that generates a math table using loops.
go
123456789101112131415
package main
import "fmt"

func main() {
    var number int
    fmt.Print("Enter a number to generate its table: ")
    fmt.Scan(&number)

    fmt.Printf("\n--- Multiplication Table for %d ---\n", number)
    
    for i := 1; i <= 10; i++ {
        result := number * i
        fmt.Printf("%d x %d = %d\n", number, i, result)
    }
}

9. Common Mistakes

  • Infinite Loops by Accident: Forgetting to include count++ in a while-style loop. The condition never becomes false, freezing the program and maxing out a CPU core.
  • Off-by-One Errors: Using < 5 instead of <= 5 when you actually want the loop to run exactly 5 times starting from 1.

10. Best Practices

  • Keep Loops Small: If the code inside your for loop is 100 lines long, extract it into a separate Function. Loops should be clean and easy to read.

11. Exercises

  1. 1. Write a for loop that prints all even numbers from 2 to 20.
  1. 2. Write a while-style for loop that creates a countdown timer from 10 to 1, then prints "Liftoff!".

12. MCQs with Answers & Explanations

Question 1

How many different loop keywords does Go have?

Question 2

Which part of a standard for loop executes ONLY ONCE at the very beginning?

Question 3

How do you write a while loop in Go?

Question 4

How do you create an infinite loop in Go?

Question 5

What does the break statement do?

Question 6

What does the continue statement do?

Question 7

What causes an accidental infinite loop?

Question 8

What keyword is heavily used in Go to loop over arrays, slices, and maps automatically?

Question 9

What is the output of for i := 0; i < 3; i++ { fmt.Print(i) }?

Q10. Can you place a for loop inside another for loop? a) Yes, this is called a nested loop b) No, the compiler prevents it Answer: a) Yes, this is called a nested loop.

13. Interview Preparation

Interview Questions:
  1. 1. Why did the creators of Go decide to exclude the while keyword from the language? (Answer: Minimalism. for can replicate while perfectly, making the language smaller and easier to read).
  1. 2. What happens if you run an infinite loop for {} on a backend server without any blocking code (like listening for network requests)? (Answer: It will consume 100% of a CPU core instantly).

14. Summary

Automation is the core of programming. Go provides a single, highly flexible loop keyword: for. It can act as a standard counter, a conditional while loop, or run infinitely. Control keywords like break and continue give you fine-grained control over execution flow.

15. Next Chapter Recommendation

Up until now, we've written all our code straight down inside main(). As programs grow, this becomes unreadable. In Chapter 9: Functions in Go, we will learn how to break our code into small, reusable, organized blocks.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·