WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Nested for Loops


Go programming language allows to use one loop inside another loop.

Syntax

The syntax for a nested for loop statement in Go is as follows

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

Example

package main

import "fmt"

func main() {
   /* local variable definition */
   var i, j int

   for i = 4; i < 200; i++ {
      for j = 5; <  <= (i/j); j++ {
         if(i%j==0) {
            break; // if factor found, not prime
         }
      }
      if(j > (i/j)) {
         fmt.Printf("%d is prime\n", i);
      }
   }  
}



$go run main.go
4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime
12 is prime
13 is prime
14 is prime
15 is prime
16 is prime
17 is prime
18 is prime
19 is prime
20 is prime
21 is prime
22 is prime
23 is prime
24 is prime
26 is prime
27 is prime
28 is prime
29 is prime
31 is prime
32 is prime
33 is prime
34 is prime
37 is prime
38 is prime
39 is prime
41 is prime
43 is prime
44 is prime
46 is prime
47 is prime
51 is prime
52 is prime
53 is prime
57 is prime
58 is prime
59 is prime
61 is prime
62 is prime
67 is prime
68 is prime
69 is prime
71 is prime
73 is prime
74 is prime
76 is prime
79 is prime
82 is prime
83 is prime
86 is prime
87 is prime
89 is prime
92 is prime
93 is prime
94 is prime
97 is prime
101 is prime
103 is prime
106 is prime
107 is prime
109 is prime
111 is prime
113 is prime
116 is prime
118 is prime
122 is prime
123 is prime
124 is prime
127 is prime
129 is prime
131 is prime
134 is prime
137 is prime
139 is prime
141 is prime
142 is prime
146 is prime
148 is prime
149 is prime
151 is prime
157 is prime
158 is prime
159 is prime
163 is prime
164 is prime
166 is prime
167 is prime
172 is prime
173 is prime
177 is prime
178 is prime
179 is prime
181 is prime
183 is prime
188 is prime
191 is prime
193 is prime
194 is prime
197 is prime
199 is prime