0

i want to out from second looping to first looping (like break) but after break i dont want to print fmt.Println("The value of i is", i). How is the algorithm?

package main

import "fmt"

func main() {
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                break
            } else {
                fmt.Println("j = ", j)
            }
        }
        fmt.Println("The value of i is", i)
    }
}
hugo iman
  • 11
  • 3

1 Answers1

1

Edit: You edited you code, so here's the edited answer for that.

To continue the outer loop from the inner (breaking the inner loop and skipping the rest of the outer loop), you have to continue the outer loop.

To address the outer loop with the continue statement use a label:

outer:
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                continue outer
            } else {
                fmt.Println("j = ", j)
            }
        }
        fmt.Println("The value of i is", i)
    }

This will output (try it on the Go Playground):

j =  0
j =  1
Breaking out of loop
j =  0
j =  1
Breaking out of loop

Original answer:

break always breaks from the innermost loop (more specifically a for, switch or select), so after that the outer loop will continue with its next iteration.

If you have nested loops and from an inner loop you want to break from the outer loop, you have to use labels:

outer:
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                break outer
            }
            fmt.Println("The value of j is", j)
        }
    }

This will output (try it on the Go Playground):

The value of j is 0
The value of j is 1
Breaking out of loop
icza
  • 389,944
  • 63
  • 907
  • 827