Go language nested loops
The Go language allows users to use loops within loops. Next, we will introduce the use of nested loops.
Syntax
The following is the format of nested loops in the Go language:
for [condition | ( init; condition; increment ) | Range]
{
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
statement(s);
}
{
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
statement(s);
}
Example
The following example uses nested loops to output the prime numbers between 2 and 100:
Example
package main
import "fmt"
func main() {
/* Define local variables */
var i, j int
for i=2; i < 100; i++ {
for j=2; j <= (i/j); j++ {
if(i%j==0) {
break; // If a factor is found, then it is not a prime number
}
}
if(j > (i/j)) {
fmt.Printf("%d is a prime number\n", i);
}
}
}
import "fmt"
func main() {
/* Define local variables */
var i, j int
for i=2; i < 100; i++ {
for j=2; j <= (i/j); j++ {
if(i%j==0) {
break; // If a factor is found, then it is not a prime number
}
}
if(j > (i/j)) {
fmt.Printf("%d is a prime number\n", i);
}
}
}
The output of the above example 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 是素数other extensions