Introduction
The for loop in Go is a versatile tool for iterating over a block of code multiple times. In this article, we'll explore the syntax and functionality of the for loop in Go, accompanied by various examples and their outputs.
Understanding the For Loop
The for loop in Go executes a block of code repeatedly until a specified condition is met. Each iteration of the loop is called an iteration.
Syntax
for initialization; condition; post {
// code block to be executed for each iteration
}
Initialization: Initializes the loop counter value.
Condition: Evaluated for each loop iteration. If it evaluates to
true
, the loop continues. If it evaluates tofalse
, the loop ends.Post: Increases or modifies the loop counter value.
For Loop Examples
Example 1: Printing Numbers from 0 to 4
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
Output:
0
1
2
3
4
Example 2: Counting to 100 by Tens
package main
import "fmt"
func main() {
for i := 0; i <= 100; i += 10 {
fmt.Println(i)
}
}
Output:
0
10
20
30
40
50
60
70
80
90
100
The continue
Statement
The continue
statement is used to skip one or more iterations in the loop and continue with the next iteration.
Example: Skipping the Value of 3
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}
Output:
0
1
2
4
The break
Statement
The break
statement is used to terminate the loop execution prematurely.
Example: Breaking Out of the Loop at 3
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
break
}
fmt.Println(i)
}
}
Output:
0
1
2
Nested Loops
Nested loops are loops placed inside another loop.
Example: Nested Loop Printing Adjectives with Fruits
package main
import "fmt"
func main() {
adj := [2]string{"big", "tasty"}
fruits := [3]string{"apple", "orange", "banana"}
for i := 0; i < len(adj); i++ {
for j := 0; j < len(fruits); j++ {
fmt.Println(adj[i], fruits[j])
}
}
}
Output:
big apple
big orange
big banana
tasty apple
tasty orange
tasty banana
The range
Keyword
The range
keyword in Go is used to iterate over arrays, slices, or maps, returning both the index and the value.
Example: Iterating Over an Array with Range
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)
}
}
Output:
0 apple
1 orange
2 banana
In summary, the for loop in Go provides a concise and effective way to execute code repeatedly, with support for skipping and terminating iterations, as well as nested loop structures. Understanding and mastering the for loop is essential for writing efficient and scalable Go programs. Experiment with different loop variations to tackle a wide range of programming challenges effectively.