Loops with for and week 2 review
Repeating tasks is what makes computers valuable. Go has a single keyword for all loops: for. There is no while or do-while; the same for adapts to three different forms. This design decision reduces what you must learn and still covers every case. By the end of this lesson you will be able to walk over ranges of numbers, repeat while a condition holds, walk over texts and collections, and control the loop with break and continue.
The three forms of for
The classic form has three parts separated by semicolons: initialization, condition and step, as in for i := 0; i < 5; i++. The second form only has a condition and is equivalent to the while of other languages: for n < 100. The third has nothing, for { }, and is an infinite loop that is broken with break or return; it is used in servers and reading loops. Inside any of them, break exits the loop and continue jumps to the next iteration.
package main
import "fmt"
func main() {
// classic form
sum := 0
for i := 1; i <= 5; i++ {
sum += i
}
fmt.Println(sum) // 15
// condition only (like while)
n := 1
for n < 100 {
n *= 2
}
fmt.Println(n) // 128
// infinite loop with break and continue
count := 0
for {
count++
if count%2 == 0 {
continue // skip even numbers
}
if count > 7 {
break
}
fmt.Print(count, " ") // 1 3 5 7
}
fmt.Println()
}for range
To walk over collections and texts you use for with range. Over a string it gives the byte index and the rune; over a slice (you will see it in week 4) it gives the index and the element; over a map it gives key and value. If you do not need one of the two values, discard it with the underscore; if you only need the index, write for i := range. Since Go 1.22 you can also write for i := range 5 to repeat five times with i from 0 to 4, and since Go 1.22 each iteration has its own copy of the loop variable, which avoids a classic bug with closures and goroutines.
package main
import "fmt"
func main() {
for i := range 3 { // Go 1.22+
fmt.Println("round", i)
}
for _, r := range "Go!" {
fmt.Printf("%c|", r)
}
fmt.Println()
// labeled break exits the outer loop
found := false
outer:
for a := 1; a <= 9; a++ {
for b := 1; b <= 9; b++ {
if a*b == 42 {
fmt.Println(a, b)
found = true
break outer
}
}
}
fmt.Println(found)
}Week 2 review
This week you learned arithmetic, comparison and logical operators, the difference between bytes and runes in a string, the strings package, decisions with if and switch, and loops with for in all its forms. With that you can already write programs that process data and make decisions. Practice with the exercise and then answer the review quiz; if you miss any question, go back to the matching lesson before moving on to functions.
اختبر ما تعلمته
السؤال 1 من 6What is the result of 7 / 2 with integers in Go?
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف