For Loops in Go

In Go, the for loop is used to execute a block of code a specific number of times until a specified condition is met. The for loop is the only loop available in Go lang (no while loops).

Syntax:
for initialization; condition; increment {
//code block

}

In the above syntax:

  • The initialization part initializes and/or declares a variable.
  • The condition is the boolean expression that returns true or false. If the condition returns true then the code block is executed.
  • The increment part increments or decrements the value of a variable declared in the initialization part.
  • The condition is evaluated again and the code is executed until the condition evaluates to false.
  • When the condition is false, the for loop ends.

In the following example, the for loop is used to print numbers 1 to 5.

Example: For Loop
package main
import "fmt"

func main() {

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

} 
Output:
1
2
3
5

In the above example, an integer variable num is declared and initialized with 1. This value is checked with the condition, num <= 5 which here is true (1 is less than 5). The code within the for loop is then executed for this value and 1 is printed. Next, the value is incremented to num++ i.e. to 2. This value satisfies the condition num <= 5, and 2 is printed. The same is repeated until the num value is no longer less than or equal to 5 (when num value is 6) and the loop exits after printing 1 through 5.

In the following example, the num variable's initial value is set to 10. The increment value is set to 5 and the loop iterates as long as the condition num <= 25 is satisfied. When num becomes greater than 25, the loop exits.

Example: For Loop
package main
import "fmt"

func main() {
    
    for num := 10; num <= 25; num += 5 {
        fmt.Println(num)
    }

}
Output:
10
15
20
25

The curly braces are mandatory in the for loop and the opening braces should be in the same line as the for statement.

Example: Invalid braces
for num := 10; num <= 25; num += 5 
{ //invalid
	fmt.Println(num)
} 
Output:
# example
./prog.go:6:32: syntax error: unexpected newline, expecting { after for clause

Continue Keyword

The continue keyword is used to skip an iteration and then continue with the next iteration. Taking the previous example of printing 1 through 5, use the continue keyword to skip printing 4.

Example: Continue Keyword
for num := 1; num <= 5; num++ {
	if num == 4 {
		continue //continue next iteration
	}
	fmt.Println(num)
} 
Output:
1
2
3
5

Break Keyword

The break keyword is used to break the execution of code and exit the for loop.

In the following example, the code stops execution and exits the loop when num equals 4.

Example: break Keyword
for num := 1; num <= 5; num++ {
	if num == 4 {
		break //exit for loop from here
	}
	fmt.Println(num)
} 
Output:
1
2
3

Range Keyword

The range keyword is used to iterate through an array, slice, or map.

Syntax:
for num, val := range myArray {
    // statements
}

In the following example, a string array colors is initialized in the main function. The num and val are two variables in the for loop, where the num variable will hold an index of the array and the val variable will hold the value.

Example: Iterate Arrays with Range Keyword
package main
import "fmt"

func main() {
	colors := [] string{"Red",  "Yellow",  "Green"}

	for num, val := range colors {
		fmt.Println (num,"-", val)
	}
}
Output:
0 - Red
1 - Yellow
2 - Green	

In the above example, if you want to print only the value and not the index, then you can use the underscore _ instead of the variable name, as shown below.

Example: _ with Range
package main
import "fmt"

func main() {
	colors := [] string{"Red",  "Yellow",  "Green"}
    
    for _ , val := range colors {
        fmt.Println(val)
    }
}
Output:
Red
Yellow
Green	

Note: A variable that is declared in a program has to be used else you get an error.

Nested For Loop

A for loop is nested within another for loop. For every iteration of the outer loop, the inner loop is executed once.

Example: Nested For Loop
package main
import ("fmt")

func main() {

    // outer loop
    for i :=0; i < 2; i++ {

      // inner loop 
        for j :=0; j < 3; j++ {
          fmt.Println ("i=",i,"j=", j )
        }

      }

}

In the above nested loop program, the first for loop (outer loop) iterates through0 and 1 and the inner for loop iterates from zero to two. For each iteration of the outer loop, the inner loop is executed once.

Output:
i= 0 j= 0
i= 0 j= 1
i= 0 j= 2
i= 1 j= 0
i= 1 j= 1
i= 1 j= 2