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,
- Define a function named
printFibonacci
that takes one parametern
of typeint
. - Initialize two variables,
a
andb
, to 0 and 1 respectively. - Use a
for
loop to iteraten
times. - In each iteration, print
a
and updatea
andb
to the next numbers in the sequence. - 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