For Loops

2-minute read
Table of Contents

We can repeat lines of code by using a for loop in Golang. It is Go’s only looping construct. Other languages have while, do-while constructs, go-to statements, etc. for looping but Go avoids the confusion by giving us a versatile iterative construct to work with.

Single condition

We can use a for loop like a while loop where we have a single condition and change the sentinel value (i) within the loop:

package main

import "fmt"

func main() {
	i := 0
	for i < 5 {
		fmt.Println("i:", i)
		i++
	}
}
for-while.go
Copy

C-styled for loop (initial; condition; after)

We can initialize the sentinel value, specify a condition for continuation of the loop and define the action to do after each iteration:

package main

import "fmt"

func main() {
	for i := 0; i < 5; i++ {
		fmt.Println("i:", i)
	}
}
for-classic.go
Copy

Range over a number

In short form, we can loop from $0$ to a value $n$ by using the format:

package main

import "fmt"

func main() {
	for i := range 5 {
		fmt.Println("i:", i)
	}
}
for-n.go
Copy

Infinite loop

We can have a for loop that runs for an indefinite number of times:

package main

import "fmt"

func main() {
	for {
		fmt.Println("hello")
	}
}
for-infinite.go
Copy

You will have to interrupt the program in order for the loop to stop running.

Continue and break

We can use the continue statement to skip to the next iteration of the loop:

package main

import "fmt"

func main() {
	for i := range 10 {
		// skip when i is divisible by 3
		if i%3 == 0 {
			continue
		}
		fmt.Println("i:", i)
	}

	fmt.Println("end of program")
}
for-continue.go
Copy

When the value of i is a multiple of $3$ (divisible by $3$), the loop will jump to the next iteration instead of printing the value of i. The break statement is used to exit the loop regardless of the current state of the loop. The execution flow continues where the loop ends:

package main

import "fmt"

func main() {
	for i := range 10 {
		// break out of the loop when i is 7
		if i == 7 {
			break
		}
		fmt.Println("i:", i)
	}

	fmt.Println("end of program")
}
for-break.go
Copy

Here the loop is exited when the value of i becomes $7$.

Support us via BuyMeACoffee