Go Loops


Loops in Go Programming

Loops in Go allow executing a block of code multiple times until a specific condition is met. The primary looping construct in Go is the for loop. Unlike other languages that support multiple loop types (like while and do-while), Go uses only for, which can be adapted to different looping scenarios.


Types of Loops in Go

Go provides three main ways to use the for loop:

  • Traditional for Loop (with Initialization, Condition, and Post Statement)
  • For Loop as a while Loop (Condition Only)
  • Infinite Loop (without Condition)

1. Traditional for Loop

This structure is similar to loops found in C, C++, and Java. It consists of three components:

  • Initialization: Executed once before the loop starts.
  • Condition: Checked before each iteration; the loop continues as long as this evaluates to true.
  • Post statement: Executed after each iteration.

Syntax:

for initialization; condition; post {
    // Code that runs during each iteration.
}

Example: Printing Numbers from 1 to 5

package main

import "fmt"

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

Output:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

2. for as a While Loop

Go does not have a separate while keyword. Instead, a for loop without an initialization or post-statement behaves like a while loop.

Syntax

for condition {
    // Code block
}

Example

package main

import "fmt"

func main() {
    num := 1
    for num <= 5 {
        fmt.Println("Number:", num)
        num++
    }
}

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

3. Infinite Loop

A for loop without any condition runs indefinitely unless stopped using a break statement.

Syntax

for {
    // Infinite loop
}

Example

package main

import "fmt"

func main() {
    count := 0
    for {
        if count == 3 {
            break // Exit the loop
        }
        fmt.Println("Looping...")
        count++
    }
}

Output:

Looping...
Looping...
Looping…

4. Loop with break Statement

The break statement is used to terminate the loop before the condition becomes false.

Example

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 4 {
            break // Stops the loop when i is 4
        }
        fmt.Println("Value:", i)
    }
}

Output:

Value: 1
Value: 2
Value: 3

5. Loop with continue Statement

The continue statement skips the current iteration and proceeds to the next one.

Example

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            continue // Skips printing when i is 3
        }
        fmt.Println("Step:", i)
    }
}

Output:

Step: 1
Step: 2
Step: 4
Step: 5

6. Nested Loops

Go allows loops inside loops, useful for working with matrices or complex iterations.

Example

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 2; j++ {
            fmt.Println("Outer:", i, "Inner:", j)
        }
    }
}

Output:

Outer: 1 Inner: 1
Outer: 1 Inner: 2
Outer: 2 Inner: 1
Outer: 2 Inner: 2
Outer: 3 Inner: 1
Outer: 3 Inner: 2

7. Looping Over an Array

Using for to iterate through an array.

Example

package main

import "fmt"

func main() {
    numbers := [3]int{10, 20, 30}
    for i, val := range numbers {
        fmt.Println("Index:", i, "Value:", val)
    }
}

Output:

Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30

8. Looping Over a Map

The range keyword helps iterate over key-value pairs in a map.

Example

package main

import "fmt"

func main() {
    students := map[string]int{"Alice": 25, "Bob": 22, "Charlie": 28}
    
    for name, age := range students {
        fmt.Println(name, "is", age, "years old")
    }
}

Output:

Alice is 25 years old
Bob is 22 years old
Charlie is 28 years old

9. Looping Over a String

A for loop can iterate over a string to access individual characters.

Example

package main

import "fmt"

func main() {
    text := "GoLang"
    
    for index, char := range text {
        fmt.Printf("Index: %d, Character: %c\n", index, char)
    }
}

Output:

Index: 0, Character: G
Index: 1, Character: o
Index: 2, Character: L
Index: 3, Character: a
Index: 4, Character: n
Index: 5, Character: g

10. Loop with Labels

Labels allow breaking out of nested loops.

Example

package main

import "fmt"

func main() {
outerLoop:
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i == 2 && j == 2 {
                break outerLoop
            }
            fmt.Println("i:", i, "j:", j)
        }
    }
}

Output:

i: 1 j: 1
i: 1 j: 2
i: 1 j: 3
i: 2 j: 1

Conclusion

Go simplifies loop constructs by using only the for keyword in various forms. It can function like a traditional for, while, or even an infinite loop. Additional control statements such as break, continue, and labeled loops offer flexibility in controlling execution flow.

PreviousNext