Go Lesson 13 – For Loops | Dataplexa

For Loops in Go

Loops allow a program to execute a block of code repeatedly. In Go, there is only one looping construct — the for loop.

Despite having a single loop keyword, Go’s for loop is extremely flexible and can replace traditional while and do-while loops found in other languages.


Basic For Loop

The most common form of a for loop includes:

  • Initialization
  • Condition
  • Increment / Decrement
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}

This loop prints numbers from 1 to 5. The variable i starts at 1 and increases by 1 on each iteration.


Using For Loop for Calculations

Loops are often used for mathematical calculations such as sums or totals.

package main

import "fmt"

func main() {
    sum := 0

    for i := 1; i <= 10; i++ {
        sum += i
    }

    fmt.Println("Total:", sum)
}

Here, the loop calculates the sum of numbers from 1 to 10.


For Loop Without Initialization

You can omit the initialization part if the variable is already declared.

package main

import "fmt"

func main() {
    i := 1

    for i <= 5 {
        fmt.Println(i)
        i++
    }
}

This behaves like a traditional while loop in other languages.


Infinite For Loop

A loop without any condition runs forever. This is commonly used in servers, listeners, or background workers.

package main

import "fmt"

func main() {
    count := 1

    for {
        fmt.Println("Count:", count)
        count++

        if count > 3 {
            break
        }
    }
}

The loop exits using the break statement.


Using Break in a Loop

The break keyword immediately stops loop execution.

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 5 {
            break
        }
        fmt.Println(i)
    }
}

This loop stops when i becomes 5.


Using Continue in a Loop

The continue keyword skips the current iteration and moves to the next one.

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            continue
        }
        fmt.Println(i)
    }
}

The number 3 is skipped, but the loop continues running.


Real-World Example: Processing Orders

Loops are often used to process lists of values such as prices or quantities.

package main

import "fmt"

func main() {
    prices := []int{120, 250, 99, 300}
    total := 0

    for i := 0; i < len(prices); i++ {
        total += prices[i]
    }

    fmt.Println("Total Amount:", total)
}

This example calculates the total cost of multiple items.


Best Practices for For Loops

  • Keep loop conditions simple
  • Avoid infinite loops unless required
  • Use break and continue sparingly
  • Prefer readable loops over clever tricks

What’s Next?

In the next lesson, you will learn about Arrays in Go, which allow storing multiple values of the same type in a fixed-size structure.