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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete