0
0
Goprogramming~5 mins

For loop basics in Go

Choose your learning style9 modes available
Introduction
A for loop helps you repeat actions many times without writing the same code again and again.
When you want to count from 1 to 10 and do something each time.
When you have a list of names and want to greet each person.
When you want to add numbers from 1 to 100.
When you want to repeat a task until a condition changes.
Syntax
Go
for initialization; condition; post {
    // code to repeat
}
The loop runs while the condition is true.
Initialization runs once at the start, post runs after each loop.
Examples
Prints numbers 0 to 4, increasing i by 1 each time.
Go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}
Counts down from 10 to 1.
Go
for i := 10; i > 0; i-- {
    fmt.Println(i)
}
Prints "Hello" three times.
Go
for i := 0; i < 3; i++ {
    fmt.Println("Hello")
}
Sample Program
This program prints the word "Number" followed by numbers 1 to 5, each on a new line.
Go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println("Number", i)
    }
}
OutputSuccess
Important Notes
You can leave out parts of the for loop to create different loop styles.
Be careful to change the loop variable, or the loop might run forever.
Go only has one loop type: the for loop, but it can do many jobs.
Summary
A for loop repeats code while a condition is true.
It has three parts: start, check, and change.
Use it to do tasks many times without writing code again.