Go:Go While Loop Simulation: Conditional and Infinite Loops
Go•Loops

Go While Loop Simulation: Conditional and Infinite Loops

Learn how Go expresses while loops using for condition and infinite server loops with for {}.

Syntax

for condition {} for {} // Infinite loop

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
for conditionLoop PatternReplaces while in C/Java.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

func main() {
    countdown := 3
    fmt.Println("--- Rocket Countdown ---")
    // While-style loop in Go
    for countdown > 0 {
        fmt.Printf("T-minus %d...\n", countdown)
        countdown--
    }
    fmt.Println("Liftoff! 🚀")

    // Controlled loop
    power := 1
    steps := 0
    for power < 50 {
        power *= 2
        steps++
    }
    fmt.Printf("\nDoubled %d times to reach %d\n", steps, power)
}
Expected Output:
--- Rocket Countdown ---
T-minus 3...
T-minus 2...
T-minus 1...
Liftoff! 🚀

Doubled 6 times to reach 64

How It Works: Step-by-Step

  • Lines 8-11: for countdown > 0 executes body while condition is true.
  • Lines 16-19: Doubles power until reaching or exceeding 50.

Key Concepts

  • Go deliberately omitted while and do-while to keep the language keyword count small.
  • for condition {} provides the exact behavior of while.

Common Mistake: Trying to write while (cond) in Go

while is not a keyword in Go; attempting to use it causes a compile error.

❌ Incorrect
while (x > 0) {} // Compile Error: undefined: while
✅ Correct
for x > 0 {} // Idiomatic Go

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler