Golang Loop – For Loop | Iteration

Golang For Loop

In this blog, we will learn about Iteration i.e Golang For Loop. Iteration is an important part of every programming language and thus Golang has kept it simple.

What we will learn about Golang For Loop:

  • Golang For Loop
    • Golang For Loop Syntax
    • Continue and break keywords in Golang
    • Looping through collections

Before Learning about Golang For-Loops, know the basics of Golang:

Golang For Loop

for <Initializer> ; <test_condition> ; <increment_operator> { // Statement (s) }

For Loop is the single most loop used in Go Language and thus Go has kept the language simple by just implementing a single kind of loop.

We can use for loops present in Go Language in many different ways so we do not feel the use of other loops like while loop and do-while loop which are present in different languages like (C, C++, Java, Python, etc.)

Example of Golang For Loop:

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

Output:

1
2
3
4
5

Golang For Loop Multiple Variables

In C, C++, Java, Python we can use two variables in For-Loop but can we do the same in Go For-Loop.

First see what we used to do in C++ Language For-Loop.

Example (C++):

    int i,j;
    for(i =0,j = 0; i<=5;i++,j++)
    {
        std::cout<<i<<" "<<j<<std::endl;
    }

Output:

0 0 1 1 2 2 3 3 4 4 5 5

But, we cannot do the same in Golang. Golang doesn’t understand comma(,) Operator to separate statements and thus this syntax isn’t possible.

	for i := 0, j:=0; i <= 5; i++, j++ {
		fmt.Println(i, j)

	}

Error: – syntax error: unexpected :=, expecting {

Let’s see an approach to do the same in Golang for loop.

	for i, j := 0, 0; i <= 5; i, j = i+1, j+1 {
		fmt.Println(i, j)

	}

Output:

0 0
1 1
2 2
3 3
4 4
5 5

Golang For Loop – Outside Initialization

In Go Language it is not a compulsory thing to initialize variable in for-loop to use it as an iterator. we can make use of pre-initialized variables in go for-loop.

To make use of pre-initialized variables in Golang For-Loop, leave the initialization part and terminate it with using semi-colon (;).

If you don’t use golang compiler will ask you for initialization.

package main

import (
	"fmt"
)

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

	}

}

Error:

.\main.go:9:18: syntax error: unexpected {, expecting semicolon or newline
.\main.go:10:18: syntax error: i++ used as value

when semi-colon is provided the compiler will not give you an error.

Example:

	i := 0
	for ; i <= 5; i++ {
		fmt.Println(i)

	}

Output:

0
1
2
3
4
5

Golang For Loop Scope

When we are using an iterator variable in for-loop it’s scope is only limited to for-loop.

If the for-loop variable matches the function level scoped variable, the for loop will not affect the global variable, because for-loop variables have only for-loop scope.

Example:

	i := 12
	for i := 0; i <= 5; i++ {
		fmt.Println(i)
	}
	fmt.Println("Global i :", i)

Output:

0
1
2
3
4
5
Global i : 12

Golang Global variables in For loop

func main() {
	i := 12
	for ; i <= 15; i++ {
		fmt.Println(i)
	}
	fmt.Println("Global i :", i)

}

Output:

12
13
14
15
Global i : 16

In this case, we are using the variable ‘i’ which is the main function scoped and its value will be changed when used in for loop.

Golang Infinite Loop

Actually, Golang doesn’t put us in an infinite loop and it gives an error whenever the compiler thinks the process is taking too long to execute, and thus the infinite loop is not achieved.

Omitting increment operator in Golang for loop can help us to achieve infinite loop.

Examples of Infinite loop in Golang.

	i := 12
	for ; i <= 15; {
		fmt.Println(i)
	}

Error: – process took too long

	n := 0

	for {

		fmt.Println(n)
	}

Output:

0……… Infinite loop

Golang While Loop

Go has only one kind of loop that is For-Loop. This makes The Go Language simple because we only have to work with one kind of loop but also hard because we have to transform the single loop to another loop for our work.

We can convert the Golang For loop to While loop.

Let’s see.

	i := 12
	for i <= 15 {
		fmt.Println(i)
		i++
	}

Output:

12
13
14
15

One More example of while loop:

Golang program to print the reverse the number.

In this case we have an unknown condition and thus we have to use while loop i.e Go for loop which is transformed to while loop.

package main

import (
	"fmt"
)

func main() {
	reverse := 0
	n := 145
	for n != 0 {
		d := n % 10
		reverse = reverse*10 + d
		n /= 10
	}
	fmt.Println("Reverse :", reverse)

}

Output:

Reverse : 541

Golang Break

Break keyword is used to break from a loop when certain condition is met.

The use of the Break keyword is mainly done in an infinite loop to make an exit from the infinite loop.

	n := 0

	for {

		fmt.Println(n)
		if( n == 10 ){
			break
		}
		n++
	}

Output:

0
1
2
3
4
5
6
7
8
9
10

Golang Continue

The Continue keyword is used for skipping certain condition and not break from the loop. It only skips the loop when a certain condition is met.

Example of Continue Keyword.

Golang Program to print odd numbers.

This program can easily be made without making it complex by using the continue keyword. But this is just an example:

	i := 1

	for ; i <= 10; i++ {

		if i%2 == 0 {
			continue
		}
		fmt.Println(i)
	}

Output:

1
3
5
7
9

In this example, the continue keyword skips the even number from printing.

Golang Nested Loops

Loop inside a loop is called nested loop.

Example:

1
12
123
1234
12345

Print the pattern using Golang:

package main

import (
	"fmt"
)

func main() {

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

}

Golang Break Label

When we use the Golang break or continue keyword in the nested loops, it breaks or skips the inner loop i.e child loop and not the outer or parent loop.

	for i := 1; i <= 5; i++ {
		for j := 1; j <= i; j++ {
			if i == 3 {
				break
			}
			fmt.Print(j)
		}
		fmt.Println()
	}

Output:

1
12

1234
12345

The 3rd execution breaks and thus just an empty line is printed which is the statement of outer loop that still executes.

If you want the break or continue to work on outer loop, make use of labels.

Example:

loop:
	for i := 1; i <= 5; i++ {
		for j := 1; j <= i; j++ {
			if i == 3 {
				break loop
			}
			fmt.Print(j)
		}
		fmt.Println()
	}

Output:

1
12

Golang Range

Go for loop can also be used to loop in a collection like Arrays, Maps, Slices, etc to get key, value.

Golang range keyword is used for looping through a collection.

Golang For loop Slice

Example:

	s := []string{"Divyanshu Shekhar", "Hritul Priya"}
	for k, v := range s {
		fmt.Println(k, v)
	}

Output:

0 Divyanshu Shekhar
1 Hritul Priya

The Key Prints the indexes and the values are the real values present at the indexes.

Golang For Loop Map

	m := map[string]int{
		"DS": 17,
		"HP": 13,
	}
	for k, v := range m {
		fmt.Println(k, v)
	}

Output:

DS 17
HP 13

In this example, a map is used and thus the key changes to the key and value of the map.

when you don’t need the key and just want to work with values, you can do something like this:

for _, v := range m {
    fmt.Println(v)
}

This states that the key is not stored in memory as we don’t need it.

Read Why Golang is called the future of server-side language?

Read Official Docs to know more about Golang For Loops.

Type of Loops in Golang.

In Golang we have only one loop i.e For-Loop.
For-Loop is only used as while-loop and forEach loop.
Syntax of for-loop:
1. for initializer; test; increment {}
2. for test {}
3. for {}

Continue, break and labels in Golang

Continue keyword is used to skip the current iteration.
The break keyword breaks the loop when the condition is met.
Labels are used to continue/break the certain loop where the label is provided.
Labels are mainly used when we have to break the outer loop from the inner loop.

Looping over collections in Golang

For-loop can also be used to loop over collections like Arrays, Slices, Maps, Strings, Channels, etc.
The range keyword is used to loop over the collections.
Example:
for k, v := range collection {}

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *