Go Language Program to Display Fibonacci Series
In the Fibonacci series, the next number is the sum of the previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 etc.
Example 1. Go Program to Display Fibonacci Series,
//Go Program to Display Fibonacci Series
package main
import "fmt"
// Main function
func main() {
number := 12
PrintFibonacci(number)
}
func PrintFibonacci(number int) {
fmt.Println("Fibonacci Series till ", number, " terms:\n")
firstTerm := 0
secondTerm := 1
for i := 1; i <= number; i++ {
fmt.Print(firstTerm, ", ")
// compute the next term
nextTerm := firstTerm + secondTerm
firstTerm = secondTerm
secondTerm = nextTerm
}
fmt.Println("\n ")
}
Output:
Example 2. Input number from standard input,
//Go Program to Display Fibonacci Series
package main
import "fmt"
// Main function
func main() {
var number int
fmt.Println("Enter an integer value : ")
_, err := fmt.Scanf("%d", &number)
if err != nil {
fmt.Println(err)
}
PrintFibonacci(number)
}
func PrintFibonacci(number int) {
fmt.Println("Fibonacci Series till ", number, " terms:\n")
firstTerm := 0
secondTerm := 1
for i := 1; i <= number; i++ {
fmt.Print(firstTerm, ", ")
// compute the next term
nextTerm := firstTerm + secondTerm
firstTerm = secondTerm
secondTerm = nextTerm
}
fmt.Println("\n ")
}
Output:
Example 3. Go Program to Display Fibonacci Series Using Recursion,
//Go Program to Display Fibonacci Series
package main
import "fmt"
// Main function
func main() {
number := 10
fmt.Println("Fibonacci Series till ", number, " terms:\n")
for i := 0; i < number; i++ {
fmt.Printf("%d ", PrintFibonacci(i))
}
}
func PrintFibonacci(n int) int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
return PrintFibonacci(n-1) + PrintFibonacci(n-2)
}
Output: