C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
For: We use a for-loop to iterate until the desired position in the sequence. We continually add up numbers until we reach that position.
ForReturn: We return the Fibonacci number at the designated position. This is an int value.
Golang program that computes Fibonacci sequence
package main
import "fmt"
func fibonacci(n int) int {
a := 0
b := 1
// Iterate until desired position in sequence.
for i := 0; i < n; i++ {
// Use temporary variable to swap values.
temp := a
a = b
b = temp + a
}
return a
}
func main() {
// Display first 15 Fibonacci numbers.
for n := 0; n < 15; n++ {
// Compute number.
result := fibonacci(n)
fmt.Printf("Fibonacci %v = %v\n", n, result)
}
}
Output
Fibonacci 0 = 0
Fibonacci 1 = 1
Fibonacci 2 = 1
Fibonacci 3 = 2
Fibonacci 4 = 3
Fibonacci 5 = 5
Fibonacci 6 = 8
Fibonacci 7 = 13
Fibonacci 8 = 21
Fibonacci 9 = 34
Fibonacci 10 = 55
Fibonacci 11 = 89
Fibonacci 12 = 144
Fibonacci 13 = 233
Fibonacci 14 = 377
Tip: To memoize this sequence, store the Fibonacci numbers in an array or slice. Then access those values when needed.
ArraySlicePerformance: Using a cache in this situation is far faster, especially with larger positions within the sequence.