Level: BeginnerGo Programs

Go Loop Programs with Output: Table, Factorial, Fibonacci

Updated 18 min read
Go Loop Programs featured image: output of table, factorial and Fibonacci loops

Go loop programs let your code repeat work, such as printing a times table, adding up numbers or walking through a list. In this post, you will write fourteen loop programs with their exact output, from counting 1 to 10 up to the Fibonacci series and nested loops. Then you will practice the loop questions that interviewers ask most, including the loop variable change from Go 1.22.

This post builds on Go if else programs, since most loops make a decision inside. For the theory of the for statement, read Go for loops explained with examples. We tested every program on Go 1.27.

What are Go Loop Programs?

Go loop programs repeat a block of code while a condition stays true, or once for each item in a collection. Go has only one loop keyword, for, but it can act like a classic loop, a while loop, an endless loop or a range loop.

Think of a teacher calling out roll numbers. She starts at 1, calls each number, and stops after the last student. A loop does the same thing. It has a start, a stop rule and a step.

Why Go Loop Programs Matter

Loops are everywhere in real code, so Go loop programs are worth practising well. For example, you loop over orders to find a total, over lines in a file to count words, and over users to send emails. Most coding round problems also need at least one loop.

  • Totals and counts: sum, average and count anything in a list.
  • Searching: find the largest value or the first match.
  • Patterns and tables: nested loops print grids, tables and star patterns.
  • Interviews: factorial, Fibonacci and reverse a number are asked again and again.

How Go Loop Programs Work

A classic for loop has three parts. First, the init statement runs once. Next, Go checks the condition before every pass. Then, after each pass, the post statement runs, and the cycle repeats until the condition is false.

Go loop programs flowchart showing init, condition, body and post steps
The loop runs init once, then checks the condition, runs the body and the post statement, and repeats until the condition is false.

The table below shows the four forms of for that you will use in Go loop programs.

FormSyntaxUse it for
Classicfor i := 1; i <= 5; i++ { }Counting with a step
While stylefor n > 0 { }Repeat until something changes
Endlessfor { }Servers and menus, stop with break
Rangefor i, v := range items { }Slices, strings, maps and ints

Counting Go Loop Programs

These first Go loop programs count and add numbers.

Program 1: Print 1 to 10

This is the first loop most people write. It prints the numbers 1 to 10 on one line.

package main

import "fmt"

func main() {
    // i := 1 runs once, i <= 10 is checked before each pass, i++ adds 1 after each pass
    for i := 1; i <= 10; i++ {
        fmt.Print(i, " ") // Print does not add a new line
    }
    fmt.Println() // end the line
}
1 2 3 4 5 6 7 8 9 10

i := 1 runs once, i <= 10 is checked before each pass, and i++ adds one after each pass. When i becomes 11, the condition is false and the loop stops. The output ends with a space, because we print one after every number.

Program 2: Countdown from 5 to 1

A loop can also count down. This easy example works like a rocket launch countdown.

package main

import "fmt"

func main() {
    // Start at 5, keep going while i is 1 or more, and take away 1 each time
    for i := 5; i >= 1; i-- {
        fmt.Println(i)
    }
    fmt.Println("Lift off!")
}
5
4
3
2
1
Lift off!

The loop starts at 5 instead of 1. Each pass, i-- takes away one. After 1, i becomes 0, the condition i >= 1 is false, and the program prints the last line.

Program 3: Sum of the First N Numbers

This program adds 1 + 2 + 3 and so on, up to 100.

package main

import "fmt"

func main() {
    limit := 100
    sum := 0 // start the running total at 0

    for i := 1; i <= limit; i++ {
        sum += i // same as sum = sum + i
    }

    fmt.Println("Sum of 1 to", limit, "is", sum)
    // The school formula n x (n + 1) / 2 should give the same answer
    fmt.Println("Formula check:", limit*(limit+1)/2)
}
Sum of 1 to 100 is 5050
Formula check: 5050

Each pass adds the current number to sum. After 100 passes, sum holds the full total. The formula n(n+1)/2 gives the same answer, which is a nice way to test your loop.

Program 4: Multiplication Table

This program prints the 7 times table.

package main

import "fmt"

func main() {
    number := 7

    for i := 1; i <= 10; i++ {
        // %d prints a number; %2d and %3d pad it to 2 and 3 characters
        fmt.Printf("%d x %2d = %3d\n", number, i, number*i)
    }
}
7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
7 x  4 =  28
7 x  5 =  35
7 x  6 =  42
7 x  7 =  49
7 x  8 =  56
7 x  9 =  63
7 x 10 =  70

The loop counts from 1 to 10 and multiplies each count by 7. Here, the widths %2d and %3d keep the columns straight. We learned these in our Go print programs.

Program 5: Range Over an Integer

Since Go 1.22, you can range over a whole number. for i := range 5 gives 0, 1, 2, 3 and 4.

package main

import "fmt"

func main() {
    // range 5 gives the numbers 0 to 4
    for i := range 5 {
        fmt.Print(i, " ")
    }
    fmt.Println()

    // If you do not need the number, leave out the variable
    for range 3 {
        fmt.Println("Hello")
    }
}
0 1 2 3 4
Hello
Hello
Hello

The first loop starts at 0 and stops before 5. The second loop does not need the number at all, so we leave out the variable. It simply repeats three times.

Classic Interview Go Loop Programs

These are the Go loop programs you are most likely to meet in a coding round.

Program 6: Factorial of a Number

The factorial of 5 is 5 x 4 x 3 x 2 x 1, which is 120.

package main

import "fmt"

func main() {
    number := 10
    factorial := uint64(1) // uint64 holds very big whole numbers (never negative)

    // Multiply 2, 3, 4 ... up to number
    for i := 2; i <= number; i++ {
        factorial *= uint64(i) // same as factorial = factorial * i
    }

    fmt.Printf("%d! = %d\n", number, factorial)
}
10! = 3628800

We start with 1 and multiply in each number from 2 to 10. We use uint64, because factorials grow very fast. Even so, 21! is too big for 64 bits, so for larger values you need the math/big package.

Program 7: Fibonacci Series

Each Fibonacci number is the sum of the two before it.

package main

import "fmt"

func main() {
    previous := 0
    current := 1

    for i := 0; i < 10; i++ {
        fmt.Print(previous, " ")

        // Step 1: work out the next number
        next := previous + current
        // Step 2: move both numbers one place forward
        previous = current
        current = next
    }
    fmt.Println()
}
0 1 1 2 3 5 8 13 21 34

The program always keeps the last two numbers. Each pass prints one, then adds the two to get the next number. Finally, it shifts both values forward. Many Go coders write this as previous, current = current, previous+current in one line.

Program 8: Reverse a Number and Count Digits

This is a while-style loop. It keeps going while the number is greater than zero.

package main

import "fmt"

func main() {
    number := 47290
    original := number // keep a copy, because number will change
    reversed := 0
    digits := 0

    // A for loop with only a condition works like a while loop
    for number > 0 {
        lastDigit := number % 10           // Step 1: take the last digit
        reversed = reversed*10 + lastDigit // Step 2: add it to the end of reversed
        number = number / 10               // Step 3: remove the last digit
        digits++
    }

    fmt.Println("Original:", original)
    fmt.Println("Reversed:", reversed)
    fmt.Println("Digits:", digits)
}
Original: 47290
Reversed: 9274
Digits: 5

number % 10 gives the last digit, and number / 10 removes it. When no digits are left, the number is 0 and the loop stops. The reversed number loses the leading zero, because 09274 is just 9274.

Program 9: Skip with continue and Stop with break

continue jumps to the next pass. break leaves the loop at once.

package main

import "fmt"

func main() {
    for i := 1; i <= 20; i++ {
        if i%2 == 0 {
            continue // skip even numbers and go to the next pass
        }
        if i > 11 {
            break // stop the whole loop after 11
        }
        fmt.Print(i, " ")
    }
    fmt.Println()
}
1 3 5 7 9 11

Even numbers hit continue, so they never reach the print line. When i becomes 13, the break ends the loop. That is why the output stops at 11.

Range-Based Go Loop Programs

In range-based Go loop programs, range walks through a collection and gives you each index and value.

Program 10: Print Every Item in a Shopping List

This is the easiest way to use range. It visits each item in a list, one by one.

package main

import "fmt"

func main() {
    // A slice is a list of values of the same type
    shoppingList := []string{"milk", "bread", "eggs"}

    // range gives the position (index) and the item on each pass
    for index, item := range shoppingList {
        fmt.Println(index+1, item) // +1 so the list starts at 1, not 0
    }
}
1 milk
2 bread
3 eggs

On each pass, range hands you the next index and item. Go counts positions from 0, so we add 1 before printing. The loop ends by itself after the last item.

Program 11: Find the Largest in a Slice

This program finds the highest price and where it sits in the list.

package main

import "fmt"

func main() {
    prices := []int{450, 1299, 85, 760, 1299, 300}

    // Start by guessing the first price is the largest
    largest := prices[0] // [0] reads the first item
    position := 0

    for index, price := range prices {
        if price > largest {
            largest = price
            position = index
        }
    }
    fmt.Println("Largest:", largest, "at index", position)
}
Largest: 1299 at index 1

The program starts with the first price as its best guess. Each time it finds a bigger price, it updates both values. We use >, not >=, so the first 1299 wins.

Program 12: Range Over a String

Ranging over a string gives you runes, not bytes. The index jumps when a character takes more than one byte.

package main

import "fmt"

func main() {
    // A rune is one character; the euro sign uses 3 bytes
    for index, character := range "Go€!" {
        fmt.Printf("index %d: %c\n", index, character) // %c prints a character
    }
}
index 0: G
index 1: o
index 2: €
index 5: !

range reads one full character at a time and tells you the byte position where it starts. The euro sign takes 3 bytes in UTF-8, so the next index is 5, not 3.

Program 13: Range Over a Map in Sorted Order

Map order is random in Go. To print keys in order, sort them first.

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    // A map stores pairs: item name -> number in stock
    stock := map[string]int{"pen": 40, "book": 12, "bag": 5}

    // Step 1: get all the keys and sort them A to Z
    sortedItems := slices.Sorted(maps.Keys(stock))

    // Step 2: print each item with its stock
    for _, item := range sortedItems {
        fmt.Println(item, stock[item]) // stock[item] looks up the value
    }
}
bag 5
book 12
pen 40

maps.Keys returns the keys, and slices.Sorted sorts them. Then the loop prints each key with its value. Both helpers are in the standard library since Go 1.23.

Program 14: Nested Loops for a Times Grid

A loop inside a loop is a nested loop. The inner loop runs fully for each pass of the outer one.

package main

import "fmt"

func main() {
    for row := 1; row <= 4; row++ { // outer loop: one pass per row
        for col := 1; col <= 4; col++ { // inner loop: one pass per column
            fmt.Printf("%4d", row*col) // %4d pads each number to 4 characters
        }
        fmt.Println() // end the row
    }
}
   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

For row 1, the inner loop prints four numbers. Then fmt.Println() ends the line, and the outer loop moves to row 2. We use nested loops a lot in our pattern programs post.

Classic for vs range in Go Loop Programs

Both forms are common, so it helps to know when to pick each one. The diagram and table below compare them.

Go loop programs comparison of classic for loops and range loops
Use a classic for loop when you control the counter, and range when you visit every item.
FeatureClassic forrange
Counter controlFull: start, stop and stepFixed: every item in order
Works onAny conditionSlices, arrays, strings, maps, ints, channels
Skip or step by 2Easy, i += 2Needs continue
Gives value copyYou read items[i]Yes, v is a copy
Best forCounting, reverse loopsVisiting every element

In short, use range to visit every item, and a classic for loop when you need a custom step or direction.

Common Mistakes in Go Loop Programs

  • Off-by-one errors: i < n and i <= n differ by one pass, so check both ends.
  • Changing the value in range: the value is a copy, so value = 0 does not change the slice. Use items[i] = 0.
  • Expecting map order: map order is random, so sort the keys when order matters.
  • break inside switch: a break inside a switch only leaves the switch, not the loop.
  • Endless loops by accident: a while-style loop needs something inside that moves it toward the end.

Best Practices for Go Loop Programs

  • Prefer range for slices and maps, because it avoids index mistakes.
  • Use range over int for simple counts, which is cleaner since Go 1.22.
  • Keep loop bodies short and move big blocks into functions.
  • Use labels for nested breaks, so the code says exactly which loop it leaves.
  • Test the edges, such as zero items, one item and the last item.

Go Loop Programs Interview Questions and Answers

Interviewers use short Go loop programs to test both logic and loop rules. Every program is complete, with real output from Go 1.27.

Syntax Questions on Go Loop Programs

Q1. Does Go have a while loop?

No. Go has only for, but for condition { } works exactly like a while loop. Also, for { } with no condition is an endless loop.

Q2. What does this program print?

package main

import "fmt"

func main() {
    number := 10
    for number > 0 { // while-style loop
        fmt.Print(number, " ")
        number -= 3 // same as number = number - 3
    }
    fmt.Println("| end:", number)
}
10 7 4 1 | end: -2

The loop runs while number is above 0. After printing 1, number becomes -2, so the condition fails and the loop stops.

Q3. What does this program print?

package main

import "fmt"

func main() {
    // i starts at 0 and goes up by 2; j starts at 10 and goes down by 2
    for i, j := 0, 10; i < j; i, j = i+2, j-2 {
        fmt.Println(i, j)
    }
}
0 10
2 8
4 6

A for loop can use two variables at once. Both move on each pass, and the loop stops when they meet.

Loop Variable Questions in Go Loop Programs

Q4. What does this program print in Go 1.22 and later?

package main

import "fmt"

func main() {
    // A slice that holds small functions to run later
    var actions []func()

    for i := 0; i < 3; i++ {
        // func() { ... } is a function with no name (a closure); it remembers i
        actions = append(actions, func() { fmt.Print(i, " ") }) // append adds to the slice
    }

    // Now run each saved function
    for _, action := range actions {
        action()
    }
    fmt.Println()
}
0 1 2

Since Go 1.22, each pass of the loop gets its own copy of i, as long as your go.mod says go 1.22 or later. So every closure remembers a different value. Before Go 1.22, this printed “3 3 3”, which was a famous bug.

Q5. Does changing the value inside range change the slice?

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}

    // value is a COPY of each item
    for _, value := range numbers {
        value *= 10 // changes only the copy
    }
    fmt.Println(numbers)

    // numbers[i] is the real item in the slice
    for i := range numbers {
        numbers[i] *= 10
    }
    fmt.Println(numbers)
}
[1 2 3]
[10 20 30]

value is a copy of each item, so changing it does nothing to the slice. To change the slice, write to numbers[i].

Q6. What does this program print?

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3}
    for index, value := range numbers {
        if index == 0 {
            numbers = append(numbers, 99) // add one more item while looping
        }
        fmt.Print(value, " ")
    }
    fmt.Println(len(numbers)) // len gives the number of items
}
1 2 3 4

range reads the length once, when the loop starts. So the new item, 99, is not visited, even though the slice now has 4 items.

break and continue Questions

Q7. What does this program print?

package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        switch i {
        case 2:
            break // this leaves only the switch
        }
        fmt.Print(i, " ")
    }
    fmt.Println()
}
1 2 3

The break only leaves the switch, not the loop. So all three numbers still print. Use a label if you want to leave the loop.

Q8. How do you break out of two loops at once?

package main

import "fmt"

func main() {
outer: // a label gives the outer loop a name
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            if i*j == 4 {
                break outer // leave BOTH loops
            }
            fmt.Print(i, "x", j, " ")
        }
    }
    fmt.Println("done")
}
1x1 1x2 1x3 2x1 done

The label outer names the outer loop. break outer leaves both loops when 2 x 2 equals 4.

Q9. What does continue with a label do?

It skips to the next pass of the labelled loop. For example, continue outer stops the inner loop and moves the outer loop forward by one.

Output Questions

Q10. What does this program print?

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        defer fmt.Print(i, " ") // defer waits and runs this when main ends
    }
    fmt.Print("start ")
}
start 2 1 0

Deferred calls run when main ends, in reverse order. So the loop queues 0, 1 and 2, and they print as 2, 1, 0 after “start”.

Q11. What does this program print?

package main

import "fmt"

func main() {
    word := "héllo"
    fmt.Println(len(word)) // len counts bytes

    count := 0
    for range word { // range counts characters
        count++
    }
    fmt.Println(count)
}
6
5

len counts bytes, and “é” takes 2 bytes. But range counts characters, so the loop runs 5 times.

Q12. What does this program print?

package main

import "fmt"

func main() {
    sum := 0
    for i := 1; i <= 10; i++ {
        if i%3 != 0 {
            continue // skip numbers that do not divide by 3
        }
        sum += i
    }
    fmt.Println(sum)
}
18

The loop only adds numbers that divide by 3, which are 3, 6 and 9. Their sum is 18.

Q13. What does this program print?

package main

import "fmt"

func main() {
    number := 12345
    sum := 0
    for number != 0 {
        lastDigit := number % 10
        sum += lastDigit
        number /= 10 // remove the last digit
    }
    fmt.Println(sum)
}
15

This is the sum of digits program. It adds 5, 4, 3, 2 and 1, which gives 15.

Q14. What does this program print?

package main

import "fmt"

func main() {
    var numbers []int // an empty (nil) slice
    for index, value := range numbers {
        fmt.Println(index, value)
    }
    fmt.Println("empty loop ok")
}
empty loop ok

Ranging over a nil or empty slice is safe. The body simply never runs.

Q15. What does this program print?

package main

import "fmt"

func main() {
    values := [3]int{1, 2, 3} // [3]int is an array with a fixed size of 3
    for index, value := range values {
        values[2] = 100
        if index == 2 {
            fmt.Println(value)
        }
    }
    fmt.Println(values[2])
}
3
100

Ranging over an array works on a copy of the whole array. So value still reads the old 3, even though values[2] became 100. With a slice, value would be 100.

Q16. How do you loop backwards?

Start at the end and count down, as in for i := len(items) - 1; i >= 0; i-- { }. Since Go 1.23, you can also write for i, item := range slices.Backward(items).

Q17. When is an endless for loop useful?

It is used for servers, game loops and menus that run until the user quits. You leave it with break, return or by stopping the program.

Practice Task

FizzBuzz is one of the most famous Go loop programs in interviews. Write a program that prints all numbers from 1 to 50, but prints “Fizz” for multiples of 3, “Buzz” for multiples of 5 and “FizzBuzz” for multiples of both. Hint: check the “both” case first.

Official Resources

Quick Recap

  • Go loop programs use only for, in classic, while, endless and range forms.
  • Since Go 1.22, you can range over an int, and each loop pass gets its own variable.
  • break leaves a loop, continue skips a pass, and labels control nested loops.
  • range gives a copy of each value, so write to items[i] to change a slice.
  • Map order is random, so sort keys with slices.Sorted(maps.Keys(stock)) when order matters.

What’s Next?

Next, we use loops to test numbers. Read Go number programs with output, where we check prime, palindrome and Armstrong numbers. For more on functions used inside loops, see the Go functions guide.