Print the Fibonacci Sequence in Go



In this tutorial, we will learn how to print the Fibonacci sequence in Go. We will cover the basic concept of the Fibonacci sequence and implement a function to generate and display the sequence.


What is the Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.


Syntax

The syntax to print the Fibonacci sequence in Go is:

func printFibonacci(n int) {
    a, b := 0, 1
    for i := 0; i < n; i++ {
        fmt.Printf("%d ", a)
        a, b = b, a+b
    }
}


Example 1: Printing the Fibonacci sequence

We can use a for loop to generate and print the Fibonacci sequence up to the n-th term.

For example,

  1. Define a function named printFibonacci that takes one parameter n of type int.
  2. Initialize two variables, a and b, to 0 and 1 respectively.
  3. Use a for loop to iterate n times.
  4. In each iteration, print a and update a and b to the next numbers in the sequence.
  5. In the main function, call the printFibonacci function with a sample value.

Go Program

package main

import (
    "fmt"
)

func printFibonacci(n int) {
    a, b := 0, 1
    for i := 0; i < n; i++ {
        fmt.Printf("%d ", a)
        a, b = b, a+b
    }
    fmt.Println()
}

func main() {
    // Print the first 10 terms of the Fibonacci sequence
    printFibonacci(10)
}

Output

0 1 1 2 3 5 8 13 21 34