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.
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 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
}
}
We can use a for loop to generate and print the Fibonacci sequence up to the n-th term.
For example,
printFibonacci
that takes one parameter n
of type int
.a
and b
, to 0 and 1 respectively.for
loop to iterate n
times.a
and update a
and b
to the next numbers in the sequence.printFibonacci
function with a sample value.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)
}
0 1 1 2 3 5 8 13 21 34