For Loop
This Go code demonstrates various usage of the for loop, including basic loop structure, loop with a condition, an infinite loop with a break statement, and using continue to skip certain iterations. Let's go through each part of the code:
package main
import "fmt"
func main() {
// Basic for loop with a condition
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// For loop with an initialization statement, a condition, and a post statement
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
// Infinite loop with a break statement
for {
fmt.Println("loop")
break
}
// For loop with continue statement to skip even numbers
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}Output
1
2
3
7
8
9
loop
1
3
5Explanation:
for i <= 3 {...}: A basicforloop with a condition. It initializesito 1 and continues looping as long asiis less than or equal to 3. It prints the value ofiin each iteration and incrementsiby 1.for j := 7; j <= 9; j++ {...}: Anotherforloop with an initialization statement (j := 7), a condition (j <= 9), and a post statement (j++). It initializesjto 7, continues looping as long asjis less than or equal to 9, prints the value ofjin each iteration, and incrementsjby 1.for {...}: An infinite loop. It continually prints "loop" and breaks out of the loop using thebreakstatement after the first iteration.for n := 0; n <= 5; n++ {...}: Aforloop with an initialization statement, a condition, and a post statement. It initializesnto 0, continues looping as long asnis less than or equal to 5, incrementsnby 1 in each iteration, and prints the value ofnonly if it's an odd number (usingif n%2 == 0 { continue }to skip even numbers).
Last updated
Was this helpful?