MOCKSTACKS
EN
Questions And Answers

More Tutorials








Go Loops

For loops will repeat a block of code a set number of times. The reason they are called for loops is that you can tell your app how many times you want it to repeat to the code for. You can think about for loops as telling your app, “repeat this, for 17 times” or “repeat this, for 5 times”.

For loops use a variable to count how many times the code has been repeated, called a counter. You control how many times the loop repeats by setting where the counter starts and ends. You also set how much the counter goes up by each time the code repeats. In most scenarios, you’ll want the counter to increase by 1 each time the loop repeats.

Go for Loop

Loops are handy if you want to run the same code over and over again, each time with a different value. In Go loops we can use break to stop looping at a specific index and continue to skip looping 1 index.

Go For loop syntax


for statement1; statement2; statement3; statement4; statement5 {
   // code to be executed multiple times
}

Go for Loop Example


package main
import ("fmt")

func main() {
  for i:=0; i < 7; i++ {
    fmt.Println(i)
  }
}

Output

0
1
2
3
4
5
6

Go for Loop Example


package main
import ("fmt")

func main() {
  for i:=0; i <= 10; i+=2 {
    fmt.Println(i)
  }
}

Output

0
2
4
6
8
10

Go Continue for Loop Example


package main
import ("fmt")

func main() {
  for i:=0; i < 7; i++ {
    if i == 3 {
      continue
    }
   fmt.Println(i)
  }
}

Output

0
1
2
4
5
6

Go Break for Loop Example


package main
import ("fmt")

func main() {
  for i:=0; i < 7; i++ {
    if i == 3 {
      break
    }
   fmt.Println(i)
  }
}

Output

0
1
2





Conclusion

In this page (written and validated by ) you learned about Go Loops . What's Next? If you are interested in completing Go tutorial, your next topic will be learning about: Go Range.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.