Print Fibonacci Sequence using Recursion in Go



In this tutorial, we will learn how to print the Fibonacci sequence using recursion in Go. We will cover the basic concept of the Fibonacci sequence and implement a recursive function to generate 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 using recursion in Go is:

func fibonacci(n int) int {
    if n <= 1 {
        return n
    }
    return fibonacci(n-1) + fibonacci(n-2)
}

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


Example 1: Printing the Fibonacci sequence using recursion

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

For example,

  1. Define a function named fibonacci that takes one parameter n of type int.
  2. Check if n is less than or equal to 1. If true, return n.
  3. Otherwise, return the sum of fibonacci(n-1) and fibonacci(n-2).
  4. Define a function named printFibonacci that takes one parameter n of type int.
  5. Use a for loop to iterate n times and print the result of fibonacci(i) in each iteration.
  6. In the main function, call the printFibonacci function with a sample value.

Go Program

package main

import (
    "fmt"
)

func fibonacci(n int) int {
    if n <= 1 {
        return n
    }
    return fibonacci(n-1) + fibonacci(n-2)
}

func printFibonacci(n int) {
    for i := 0; i < n; i++ {
        fmt.Printf("%d ", fibonacci(i))
    }
    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