-
Notifications
You must be signed in to change notification settings - Fork 0
/
looping.go
100 lines (86 loc) · 1.24 KB
/
looping.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import "fmt"
func looping() {
fmt.Println("looping")
/*
Keywords:
for, continue, break
*/
for i := 0; i < 5; i++ {
fmt.Println("loop", i)
}
/*
We have have only one statement for each section
of the 'for' loop. 'i++' counts as one statement
in itself, so we cannot use it.
*/
for i, j := 0, 0; i < 5; i, j = i+1, j+2 {
fmt.Println(i, j)
}
/*
The difference is scope
*/
i := 0
for ; i < 5; i++ {
fmt.Println("loop", i)
}
/*
WHILE_LOOP
*/
for i < 5 {
fmt.Println("loop", i)
i++
}
// OR
for i < 5 {
fmt.Println("loop", i)
i++
}
/*
INFINITE_LOOP
*/
for {
fmt.Println("loop", i)
break
}
/*
Labelled code blocks
*/
CODE_BLOCK:
for i := 0; i <= 3; i++ {
for j := 0; j <= 3; j++ {
fmt.Println("CODE_BLOCK: ", i*j)
if i*j >= 3 {
break CODE_BLOCK
}
}
}
/*
Looping over slices, arrays and maps
*/
/*
Slices & arrays
*/
myArray := []int{1, 2, 3}
for k, v := range myArray {
fmt.Println(k, v)
}
/*
Maps
*/
myMap := map[string]int{
"English": 10,
"Mathematics": 20,
"Computers": 30,
}
for k, v := range myMap {
fmt.Println(k, v)
}
/*
Strings
*/
myString := "Hello Golang!"
for k, v := range myString {
fmt.Println(string(v), k, v)
}
}