Gopher

For Loop in Golang

Published on 10 May 2020
Last Updated on 10 May 2020

Unlike other programming languages, Golang does not have while, do while loops.

In Golang, for loop is the only looping construct available.

However, for loop in Golang is powerful enough to mimic behaviour of while and do while loops. We will see how to do that in the examples given below.

What loops are used for

Loops are used in situations where a block of code must be executed more than once. Loops are also useful when a number of statements must be executed sequentially. Loops can also be used to execute certain statements until a certain condition is met

Program to demonstrate simple for loop

Program given below demonstrates how to write a simple for loop in Golang.

// program to demonstrate simple for loop in Golang
package main

import "fmt"

func main() {
	for a := 1; a <= 3; a++ {
		fmt.Println("a is:",a)
	}
}

Program output

Above program produces following output:

a is: 1
a is: 2
a is: 3

Program Description

Above program demonstrates how to define a simple For loop in Golang. The first statement in above for loop is the initial variable declaration. The second statement is condition which will be checked before every iteration. Loop will execute only if the condition is true. The third statement is the increment or decrement operator, used for incrementing or decrementing value of a variable.

Program to demonstrate for loop with no condition

Program given below demonstrates a simple for loop with no condition in Golang.

// program to demonstrate a for loop with no condition in Golang
package main

import "fmt"

func main() {
	a := 0
	for {
		if a > 2 {
			break
		}
		a++
		fmt.Println("we are inside the loop")
	}
}

Program output

Above program produces following output:

we are inside the loop
we are inside the loop
we are inside the loop

Program Description

Above program demonstrates how to define a for loop with no initial variable declaration, condition check or increment / decrement.

Instead, conditions and incrementing or decrementing a variable is done inside the loop.

Program to demonstrate for loop with one condition

Program given below, makes use of only one condition check. If this condition is true then the contents inside the loop will be executed.

// program to demonstrate a for loop with one condition in Golang
package main

import "fmt"

func main() {
	a := 0
	for a < 3 {
		a++
		fmt.Println("we are inside the loop")
	}
}

Program output

Above program produces following output:

we are inside the loop
we are inside the loop
we are inside the loop

Program Description

Above program makes use of for loop that does not define an initial condition, it also does not specify an increment or decrement operator.

Nested for loops in Golang

Program given below demonstrates how a for loop can be nested inside another for loop.

// program to demonstrate nested for loop in Golang
package main

import "fmt"

func main() {
	for a := 0; a < 2; a++ {
		for b := 0; b < 2; b++ {
			fmt.Println("\na is:", a)
			fmt.Println("b is:", b)
		}
	}
}

Program output

Above program produces following output:


a is: 0
b is: 0

a is: 0
b is: 1

a is: 1
b is: 0

a is: 1
b is: 1

Program Description

Above program demonstrates how nested for loops can be used for executing a set of statements

For range loop in Golang

Program given below demonstrates how for range loop can be used for iterating over an array:

// program to demonstrate use of for range loop in Golang
package main

import "fmt"

func main() {
	// ... operator used for automatic length declaration
	var alphabets = [...]string{
		"a", "b", "c",
	}
	// for range loop used for iterating over alphabets array
	for key, value := range alphabets {
		fmt.Println("key:",key)
		fmt.Println("value:",value)
		fmt.Println("");
	}
}

Program output

Above program produces following output:

key: 0
value: a

key: 1
value: b

key: 2
value: c

Nested for range loop in Golang

Program to demonstrate nested for range loop in Golang:

// program to demonstrate nested for range loop in Golang
package main

import "fmt"

func main() {
	// ... operator used for automatic length declaration
	var alphabets = [...]string{
		"a", "b",
	}
	var numbers = [...]int{
		1, 2,
	}
	// for range loop used for iterating over alphabets array
	for key1, value1 := range alphabets {
		for key2, value2 := range numbers {
			fmt.Println("key1:", key1)
			fmt.Println("value1:", value1)
			fmt.Println("key2:", key2)
			fmt.Println("value2:", value2)
			fmt.Println("");
		}
	}
}

Program output

Above program produces following output:

key1: 0
value1: a
key2: 0
value2: 1

key1: 0
value1: a
key2: 1
value2: 2

key1: 1
value1: b
key2: 0
value2: 1

key1: 1
value1: b
key2: 1
value2: 2

Infinite loop

// program to demonstrate infinite for loop in Golang
package main

import "fmt"

func main() {
	for true {
		fmt.Println("inside infinite for loop, press CTRL + C to terminate")
	}
}

Program output

Above program produces following output:

inside infinite for loop, press CTRL + C to terminate
inside infinite for loop, press CTRL + C to terminate
inside infinite for loop, press CTRL + C to terminate
inside infinite for loop, press CTRL + C to terminate
inside infinite for loop, press CTRL + C to terminate
Process finished with exit code 2

Program Description

A for loop can become infinite for loop when its condition never becomes false. If no condition is specified while initializing a for loop then its condition is true.

It is also possible to accidentally define a for loop by declaring conditions that might never become false.

Loop control statement

  • break
  • continue
  • goto statement

Break keyword in Golang as a loop control statement

Break keyword in Golang is used inside a for loop for terminating its execution. After break statement, program execution resumes the next statement placed right after the break statement.

// program to demonstrate how to use break statement in Golang
package main

import "fmt"

func main() {
	for true {
		fmt.Println("inside for loop")
		break
	}
	fmt.Println("for loop is terminated")
}

Program output

Above program produces following output:

inside for loop
for loop is terminated

Program Description

Above program makes use of infinite for loop that is terminated using a break statement.

As shown in above program, break statement can be used for terminating a for loop, once the for loop is terminated. Program execution will continue to the next statement.

Continue keyword in Golang as a loop control statement

Continue statement is used for immediately forcing the next iteration in the loop. Continue statement forces the code between current iteration and next iteration to be skipped and program flow resumes on the next iteration.

// program to demonstrate how to use continue statement in Golang
package main

import "fmt"

func main() {
	for a := 0; a < 3; a++ {
		fmt.Println("inside for loop part 1")
		continue
		fmt.Println("inside for loop part 2")
	}
	fmt.Println("for loop is terminated")
}

Program output

Above program produces following output:

inside for loop part 1
inside for loop part 1
inside for loop part 1
for loop is terminated

Program Description

Above program demonstrates how to use continue statement in Golang to skip to the next iteration in a for loop.

fmt.Println("inside for loop part 2")

Above line in your Go program will be unreachable because of using continue statement right before it, and this line will be skipped from executing all the time making it unreachable.

Goto Statement in Golang as a loop control statement

It is usually recommended to not use Goto statement for avoiding confusion, however Golang standard library itself occasionally makes use of Goto statements for improving efficiency of the code.

Using goto statement, a code can unconditionally jump from the goto to a new label.

Labels are required for using a goto statement inside a loop in Golang. Labels can also be used with break and continue statements however, we will discuss them in a different chapter.

Syntax for a goto statement in Golang

Given below is a common syntax for a goto statement in Golang.

goto label;
..
..
..
..
label: stattement;

Here, a label can not be a go keyword but any other plain text. Label can be places above the goto keyword or below the goto keyword.

Program to demonstrate goto statements in a for loop

Given below is a program that makes use of Goto statement inside a for loop.

// program to demonstrate for loop with labels
package main

import "fmt"

func main() {
	for a := 0; a < 3; a++ {
		fmt.Println("a is:", a)
		if a == 2 {
			goto END_OF_LOOP
		}
	}
END_OF_LOOP:
	fmt.Println("Exiting loop via goto.")
}

Program output

Above program produces following output:

a is: 0
a is: 1
a is: 2
Exiting loop via goto.