Go Language Tutorial

# Go Program for Fibonacci Series

## Fibonacci Series Algorithm

Fibonacci series is an integer sequence where every number after the first two is the sum of the two preceding ones.

Fibonacci n'th term is calculated as sum of n-1'th term and n-2'th term.

```F{n}=F{n-1}+F{n-2}
where F{0} = 0 and F{1} = 1
```

## Go Program to Generate Fibonacci Series using for loop

Reads the number as user input and calculates and displays the Fibonacci series numbers till the user input number.

```package main

import "fmt"

func fibonacci(num int) {
var a,b int
for a,b=0,1;a<=num;a,b=b,a+b {
fmt.Printf("%d\t",a)
}
fmt.Println()
}

func main() {
var num int
fmt.Print("Enter number: ")
fmt.Scanf("%d", &num)
fibonacci(num)
}
```
Output:
```\$ go build fibonacci.go
\$ ./fibonacci
Enter number: 6
0	1	1	2	3	5

\$ ./fibonacci
Enter number: 8
0	1	1	2	3	5	8
```

## Go Programming to Generate Fibonacci Series using for loop with no variable declarations

This go program is same as above code but here variables used in the for loop are not declared. instead of that used (:) to define and auto initialize variable type based on defined value.

```package main

import "fmt"

func fibonacci(num int) {
for a,b:=0,1;a<=num;a,b=b,a+b {
fmt.Printf("%d\t",a)
}
fmt.Println()
}

func main() {
var num int
fmt.Print("Enter number: ")
fmt.Scanf("%d", &num)
fibonacci(num)
}
```
Output:
```\$ ./fibonacci
Enter number: 8
0	1	1	2	3	5	8
```

## Go Programming to Generate Fibonacci Series till number of terms using for loop

This go program is used to generates the fibonacci series till the number of terms which is provided as user input.

```package main

import "fmt"

func fibonacci(num int) {
for i,a,b:=0,0,1;i<num;a,b,i=b,a+b,i+1 {
fmt.Printf("%d\t",a)
}
fmt.Println()
}

func main() {
var num int
fmt.Print("Enter number: ")
fmt.Scanf("%d", &num)
fibonacci(num)
}
```
Output:
```\$ go build fibonacci.go
\$ ./fibonacci
Enter number: 5
0	1	1	2	3

\$ ./fibonacci
Enter number: 8
0	1	1	2	3	5	8	13
```