0
0
Goprogramming~5 mins

Why loops are needed in Go

Choose your learning style9 modes available
Introduction

Loops help us 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 or array.
When you want to keep asking a user for input until they give a valid answer.
When you want to perform a task multiple times, like sending emails to many people.
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 for loop.

You can leave parts empty to create different loop behaviors.

Examples
This prints numbers 1 to 5.
Go
for i := 1; i <= 5; i++ {
    fmt.Println(i)
}
This is like a while loop, printing 1 to 5.
Go
i := 1
for i <= 5 {
    fmt.Println(i)
    i++
}
This loop runs forever but stops immediately because of break.
Go
for {
    fmt.Println("Hello")
    break
}
Sample Program

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

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println("Number", i)
    }
}
OutputSuccess
Important Notes

Loops save time and make your code shorter and easier to read.

Be careful to avoid infinite loops that never stop.

Summary

Loops repeat actions without rewriting code.

Go uses the for loop for all looping needs.

Loops help handle many items or repeat tasks easily.