Go language loop nesting


Release date:2023-09-14 Update date:2023-10-13 Editor:admin View counts:327

Label:

Go language loop nesting

Go language allows users to use loops within loops. Next we will introduce you to the use of nested loops.

Grammar

The following is Go format of the language nested loop:

for [condition \|  ( init; condition; increment ) \| Range]
{
   for [condition \|  ( init; condition; increment ) \| Range]
   {
      statement(s);
   }
   statement(s);
}

Example

The following example uses loop nesting to output 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, it is not a prime number
         }
      }
      if(j > (i/j)) {
         fmt.Printf("%d is a prime number\\n", i);
      }
   }
}

The output of the above instance is as follows:

2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime number

Powered by TorCMS (https://github.com/bukun/TorCMS).