Google News
logo
Golang - Interview Questions
Write a Go program to find the nth Fibonacci number.
To find the nth Fibonacci number, we have to add the previous 2 Fibonacci numbers as shown below.
fib(0)=0
fib(1)=1
fib(2)=1+0 = 1
fib(3)=1+1 = 2
fib(4)=2+1 = 3
: 
: 
fib(n)=fib(n-1)+fib(n-2)
Code :
package main
import "fmt"
//nth fibonacci number function
func fibonacci(n int) int {
        if n < 2 {
            return n
        }
        return fibonacci(n-1) + fibonacci(n-2)
}

func main() {
    fmt.Println(fibonacci(7))
}
Output :
13
Advertisement