Skip to content

Commit 3ffa263

Browse files
committed
Add information about loops
1 parent b1e4e86 commit 3ffa263

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ I believe to get a good understanding, you can follow this order:
3737
- [Stdin & stdout](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/stdin_stdout.go)
3838
- [Arrays](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/array.go)
3939
- [Conditional statements](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/conditional_statements.go)
40-
- [Loops]()
40+
- [Loops](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/loops.go)
4141
- [Pointers](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/pointers.go)
4242
- [Structs](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/structs.go)
4343
- [Functions](https://github.com/mfbmina/data-structures-algorithms-go/blob/main/functions.go)

loops.go

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// In computer science, a loop (or for-loop) is a control flow statement for specifying iteration,
6+
// which allows code to be executed repeatedly.
7+
//
8+
// In Golang, there are three main types of for loop:
9+
// 1. While loops (which sometimes can be infinite loops)
10+
// 2. For loops
11+
// 3. Range loops
12+
func main() {
13+
array := []int{1, 2, 3, 4, 5}
14+
15+
// While loops are used to do some actions while the condition is true.
16+
// In this case, the condition is `i` being below 5.
17+
i := 0
18+
for i < 5 {
19+
fmt.Println(i, "-", array[i])
20+
i++
21+
}
22+
fmt.Println("----------")
23+
24+
// For loops are used to do some actions when you know exactly all the conditions for it.
25+
// In this case, we want to instanciate `i` with 0 and for each iteration we increase `i` by 1.
26+
// We do this while `i` is below 5.
27+
for i := 0; i < 5; i++ {
28+
fmt.Println(i, "-", array[i])
29+
}
30+
fmt.Println("----------")
31+
32+
// Range loops are the best when you want to go over a collection of elements.
33+
// In this case, we go through the array.
34+
for i, v := range array {
35+
fmt.Println(i, "-", v)
36+
}
37+
fmt.Println("----------")
38+
39+
// Loops can also be `infinite`
40+
i = -1
41+
for {
42+
i += 1
43+
44+
if i >= 5 {
45+
// `break` quits the loop execution
46+
break
47+
}
48+
49+
if i%2 == 0 {
50+
// `continue` executes the next iteration
51+
continue
52+
}
53+
54+
fmt.Println(i) //, "-", array[i])
55+
}
56+
}

0 commit comments

Comments
 (0)