Algorithm
In Go (also known as Golang), a for
loop is the primary mechanism for iterating over elements. There are different ways to use for
loops in Go, and I'll cover a few of them here.
Code Examples
#1 Basic for loop:
Code -
Golang Programming
package main
import "fmt"
func main() {
// Basic for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
This example prints numbers from 0 to 4. The syntax is for initialization; condition; post { }.
Copy The Code &
Try With Live Editor
#2 Infinite loop:
Code -
Golang Programming
package main
import "fmt"
func main() {
// Infinite loop
for {
fmt.Println("This is an infinite loop")
// To break out of the loop, use break
break
}
}
Copy The Code &
Try With Live Editor
#3 for loop with a range:
Code -
Golang Programming
package main
import "fmt"
func main() {
// Looping over a slice using range
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Copy The Code &
Try With Live Editor
#4 for loop with a single condition:
Code -
Golang Programming
package main
import "fmt"
func main() {
// Loop with a single condition
i := 0
for i < 5 {
fmt.Println(i)
i++
}
}
Copy The Code &
Try With Live Editor
Demonstration
Go Lang Programming for Loop