|
| 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