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.
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.
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()
}
We can use a recursive function to generate and print the Fibonacci sequence up to the n-th term.
For example,
fibonacci
that takes one parameter n
of type int
.n
is less than or equal to 1. If true, return n
.fibonacci(n-1)
and fibonacci(n-2)
.printFibonacci
that takes one parameter n
of type int
.for
loop to iterate n
times and print the result of fibonacci(i)
in each iteration.printFibonacci
function with a sample value.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)
}
0 1 1 2 3 5 8 13 21 34