Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - BREAK


'Break' as the name suggests, is used to break out of a loop(i.e. 'for loop') before its execution is complete.


To make it a little simpler, let us take the below example.


'Break' with 'while loop'


Say you have a 'for loop' that is used to print the numbers from 1 to 5.


Example :



package main
import "fmt"
    
func main() {
        
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}


Output :



 1
 2
 3
 4
 5

But let us say, you want to 'break' out of the 'while loop', if the value of 'x' is '3'.


i.e. You want to get out of the loop, right after printing 1, 2 and 3.


And we can achieve it using 'break' statement.


Let us modify the above program using the 'break' statement.


Example :



package main
import "fmt"
    
func main() {
        
    for i := 1; i <= 5; i++ {
              
        fmt.Println(i)
              
        if (i == 3) {
            break
        }
    }
}


Output :



 1
 2
 3

And all we have done is placed an 'if' condition, right after the print statement, checking if the value of 'x' is equal to '3'. If so we break out of the loop.


if (i == 3) {
    break
}

And the 'break' statement helps to get out of the 'for loop'.