0
0
Goprogramming~5 mins

Loop execution flow in Go

Choose your learning style9 modes available
Introduction

Loops help repeat actions many times without writing the same code again and again.

When you want to print numbers from 1 to 10.
When you need to check each item in a list one by one.
When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a task until a condition changes.
When you want to process data step by step automatically.
Syntax
Go
for initialization; condition; post {
    // code to repeat
}

The for loop is the only loop in Go and can work like a while or do-while loop.

The loop runs as long as the condition is true.

Examples
This loop prints numbers 0 to 4.
Go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
This loop uses only a condition and repeats while i is less than 3.
Go
i := 0
for i < 3 {
    fmt.Println(i)
    i++
}
This is an infinite loop that stops immediately because of break.
Go
for {
    fmt.Println("Hello")
    break
}
Sample Program

This program prints numbers from 1 to 5 using a for loop.

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Printf("Number: %d\n", i)
    }
}
OutputSuccess
Important Notes

You can use break to stop the loop early.

Use continue to skip the current loop step and move to the next.

Loops help avoid repeating code and make programs shorter and easier to read.

Summary

Loops repeat code while a condition is true.

Go uses only the for loop for all looping needs.

You can control loop flow with break and continue.