Go Language nested loop
Go language allows the user to use a loop within a loop. Next, we will introduce the use of nested loops.
grammar
Here is the Go language nested loops formats:
for [condition | ( init; condition; increment ) | Range] { for [condition | ( init; condition; increment ) | Range] { statement(s); } statement(s); }
Examples
The following example uses a nested loop to output primes 2-100 of:
package main import "fmt" func main() { /* 定义局部变量 */ var i, j int for i=2; i < 100; i++ { for j=2; j <= (i/j); j++ { if(i%j==0) { break; // 如果发现因子,则不是素数 } } if(j > (i/j)) { fmt.Printf("%d 是素数\n", i); } } }
Run the above example output is:
2 是素数 3 是素数 5 是素数 7 是素数 11 是素数 13 是素数 17 是素数 19 是素数 23 是素数 29 是素数 31 是素数 37 是素数 41 是素数 43 是素数 47 是素数 53 是素数 59 是素数 61 是素数 67 是素数 71 是素数 73 是素数 79 是素数 83 是素数 89 是素数 97 是素数