-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathloops.go
54 lines (46 loc) · 1.17 KB
/
loops.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import "fmt"
func main() {
// repeat iteration until the expression is true
// C like loop
for i := 0; i < 10; i++ {
fmt.Printf("i = %+v\n", i)
}
// omiting initialization and step
// "while" style
counter := 1
for counter < 5 {
fmt.Printf("counter = %+v\n", counter)
counter++ // don't forget this step or will run forever
}
// omiting only step
for counter := 1; counter < 5; {
fmt.Printf("counter = %+v\n", counter)
counter++ // don't forget this step or will run forever
}
// omiting only initialization
count := 1
for ; count < 5; count++ {
fmt.Printf("count = %+v\n", count)
count++ // don't forget this step or will run forever
}
// run forever unless that have a break
for {
fmt.Println("loop")
break // get out of the loop
}
// only even numbers
for n := 0; n <= 5; n++ {
// if is odd, continue loop
if n%2 != 0 {
continue
}
fmt.Println(n)
}
// for each element - arrays
// NOTE: range always returns two elements
for index, value := range [4]string{"apple", "banana", "orange", "lemon"} {
fmt.Printf("indice: %d value: %q\n", index, value)
}
// slices and map iterations will showed in respective days
}