Go for statement can repeat a list of statements multiple times.
package main/*from ww w . j a v a2 s.c o m*/ import "fmt" func main() { i := 1 for i <= 10 { fmt.Println(i) i = i + 1 } }
First, we create a variable called i
that we use to store the number.
Then we create a for loop by using the keyword for.
Go does not have a lot of different types of loops (while, do, until, foreach, ...).
Go for loop can be used in a variety of different ways.
The previous program could also have been written like this:
package main// w w w . j a va 2s.c om import "fmt" func main() { for i := 1; i <= 10; i++ { fmt.Println(i) } }
Put if statement inside for loop.
package main/*from ww w .j a v a 2s. c o m*/ import "fmt" func main() { for i := 1; i <= 10; i++ { if i % 2 == 0 { fmt.Println(i, "even") } else { fmt.Println(i, "odd") } } }