Golang’s for loop

init: It is generally an assignment expression, which assigns an initial value to the control variable;

condition: relational expression or logical expression, loop control condition;

post: It is generally an assignment expression that increments or decrements the control variable.

The execution process of the for statement is as follows:

1) First assign an initial value to the expression init;

2) Determine whether the assignment expression init satisfies the given condition, if its value is true and satisfies the loop condition, execute the statement in the loop body, then execute post, enter the second loop, and then judge the condition; otherwise, judge the value of the condition as If false, if the condition is not met, the for loop is terminated and the statement outside the loop is executed.

package main
 
import (
    "fmt"
)
 
func main() {
    for i := 1; i < 10; i++ {
        fmt.Println(i)
    }
}
package main
 
import (
    "fmt"
)
 
func main() {
    i := 0
    for i < 5 {
        i++
    }
    for i == 5 {
        fmt.Println(i)
        break
    }
}
package main
 
import (
     "fmt"
)
 
func main() {
     i := 0
     for i < 5 {
         i++
     }
     for i == 5 {
         fmt.Println(i)
         break
     }
}

loop nesting

One or more for loops can be nested in a for loop, examples are as follows:

1) Use loop nesting to output the nine-nine multiplication table:

package main
 
import "fmt"
 
func main() {
 
    for i := 1; i < 10; i++ {
        for j := 1; j <= i; j++ {
            fmt.Printf("%d * %d = %2d\t", i, j, i*j)
        }
        fmt.Println()
    }
}

2) Use loop nesting to output prime numbers between 2 and 100:

package main
 
import "fmt"
 
func main() {
    var i, j int
 
    for i = 2; i < 100; i++ {
        for j = 2; j  (i / j) {
            fmt.Printf("%2d  是素数\n", i)
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish