WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Nested for Loops


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

Syntax

The following is the format of the Go language nested loop:

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

Instance

The following example uses loop nesting to output prime numbers between 2 and 100:

example

package main

import "fmt"

func main() {
   /* Defining 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 factor is found ´╝îNo Prime number
         }
      }
      if(j > (i/j)) {
         fmt.Printf("%d  Prime number\n", i);
      }
   }  
}

The above example runs the output as:

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