For Loops in Go Programming
Introduction
In Go programming, a for loop is used to repeatedly execute a block of code as long as a specified condition is true. It is one of the most common control structures and is used to iterate over arrays, slices, maps, channels, and more.
Basic Syntax
The basic syntax of a for loop in Go is as follows:
for initialization; condition; post {
// Code to execute
}
Let's break down this syntax:
- Initialization: Executed once before the loop starts.
- Condition: Evaluated before each iteration. If true, the loop continues; otherwise, it stops.
- Post: Executed after each iteration.
Example: Basic For Loop
Here is a simple example of a for loop that prints the numbers from 1 to 5:
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
The output of the above code will be:
2
3
4
5
For Loop with Multiple Variables
Go allows you to use multiple variables in the initialization and post statements of the for loop:
package main
import "fmt"
func main() {
for i, j := 0, 10; i < 5; i, j = i+1, j-1 {
fmt.Printf("i: %d, j: %d\n", i, j)
}
}
The output of the above code will be:
i: 1, j: 9
i: 2, j: 8
i: 3, j: 7
i: 4, j: 6
For Loop with Range
The range
keyword in Go can be used to iterate over elements of an array, slice, map, or channel. Here is an example:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
The output of the above code will be:
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5
Infinite For Loop
A for loop can run indefinitely if no condition is specified. This is known as an infinite loop:
package main
func main() {
for {
// Code to execute
}
}
Use caution with infinite loops to avoid creating programs that never terminate.
Breaking Out of a For Loop
You can use the break
statement to exit a for loop prematurely:
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}
}
The output of the above code will be:
2
3
4
Continuing to the Next Iteration
You can use the continue
statement to skip the current iteration and move to the next one:
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}
The output of the above code will be:
2
4
5
Nesting For Loops
For loops can be nested to perform more complex iterations:
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
fmt.Printf("i: %d, j: %d\n", i, j)
}
}
}
The output of the above code will be:
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3