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:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example