Algorithm


Code Examples

#1 Go Lang break statement

Code - Golang Programming

package main
import "fmt"

func main() {
  for i := 1 ; i  < = 5 ; i++ {

    // terminates the loop when i is equal to 3
    if i == 3 { 
      break
    }

    fmt.Println(i)
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
1
2

#2 break-nested-loop Go break statement with nested loops

Code - Golang Programming

spackage main
import "fmt"

func main() {

  // outer for loop
  for i := 1; i  < = 3; i++ {

    // inner for loop
    for j := 1; j  < = 3; j++ {

      // terminates the inner for loop only
      if i==2 {
        break
      }

    fmt.Println("i=", i, "j=", j)
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

#3 Go Lang continue statement

Code - Golang Programming

package main
import "fmt"

func main() {
  for i := 1 ; i  < = 5 ; i++ {

    // skips the iteration when i is equal to 3
    if i == 3 {
      continue
    }

  fmt.Println(i)
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
1
2
4
5

#4 Go continue statement with nested loops

Code - Golang Programming

package main
import "fmt"

func main() {
  for i := 1; i  < = 3; i++ {
    for j := 1; j  < = 3; j++ {

      // skips the inner for loop only
      if j==2 {
        continue
      }

    fmt.Println("i=",  i, "j=",j )

    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
i= 1 j= 1
i= 1 j= 3
i= 2 j= 1
i= 2 j= 3
i= 3 j= 1
i= 3 j= 3
Advertisements

Demonstration


Go Lang Programming break and continue