0
0
Goprogramming~5 mins

For loop as while in Go

Choose your learning style9 modes available
Introduction

Sometimes you want to repeat actions until a condition changes. Using a for loop like a while loop helps you do that easily.

When you want to keep doing something until a number reaches a limit.
When you wait for a user to enter a correct input.
When you want to repeat a task but don't know how many times in advance.
Syntax
Go
for condition {
    // code to repeat
}

This form of for loop runs as long as the condition is true.

It works like a while loop in other languages.

Examples
This prints numbers 0 to 4 using a for loop as a while loop.
Go
i := 0
for i < 5 {
    fmt.Println(i)
    i++
}
This counts down from 10 to 1.
Go
count := 10
for count > 0 {
    fmt.Println("Counting down", count)
    count--
}
Sample Program

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

Go
package main

import "fmt"

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

Remember to update the variable inside the loop to avoid infinite loops.

Go does not have a separate while keyword; this for form replaces it.

Summary

Use for condition { } to repeat code while a condition is true.

This is Go's way to write a while loop.

Always change the condition inside the loop to stop it eventually.