Menu Close

Go – Program to generate fibonacci series in go

Here, We are going to write a Program to generate fibonacci series in go. In a Fibonacci sequence, each number is equal to the previous two numbers added together.

Algorithm:

  • Get the number from user
  • Calculate the fibonacci number
  • Print it
F{n} = F{n-1} + F{n-2}

where F{0} = 0 and F{1} = 1

Using loop

Example with code:

package main

import (
  "fmt"
)

func Fibonacci(n int) {

  var n3, n1, n2 int = 0, 0, 1

  for i := 1; i <= n; i++ {

    fmt.Println(n1)

    n3 = n1 + n2

    n1 = n2

    n2 = n3

  }
}

func main() {

    Fibonacci(10)

  }

Output:

0
1
1
2
3
5
8
13
21
34

Using Recursion

Example with code:

package main

import (
  "fmt"
)

func Fibonacci(n int) int {

  if n <= 1 {

    return n

  }

  return Fibonacci(n-1) + Fibonacci(n-2)

}

func main() {

  for i := 1; i <= 10; i = i + 1{

    fmt.Println(Fibonacci(i))

  }

}

Output:

1
1
2
3
5
8
13
21
34
55

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *