Write a Golang program to print the Fibonacci series

Go ProgrammingServer Side ProgrammingProgramming

Definition: In a Fibonacci series, the next number would be the summation of its two previous numbers, series starting from 0 and 1.

Examples

Print a fibonacci series up to num = 10;

Series: 1, 2, 3, 5, 8, next is 13 but greater than 10;

Approach to solve this problem

  • Step 1: Define a function that accepts a numbers(num) type is int, till then need to print the series.
  • Step 2: Take two initial numbers for the series, i.e., 0 and 1.
  • Step 3: Start a true for loop and declare a third variable to store previous two values.
  • Step 4: Print the summation of two numbers until the summation is lesser than the given num.

Program

Live Demo

package main
import "fmt"

func printFibonacciSeries(num int){
   a := 0
   b := 1
   c := b
   fmt.Printf("Series is: %d %d", a, b)
   for true{
      c = b
      b = a + b
      if b >= num{
         fmt.Println()
         break
      }
      a = c
      fmt.Printf(" %d", b)
   }
}

func main(){
   printFibonacciSeries(10)
   printFibonacciSeries(16)
   printFibonacciSeries(100)
}

Output

Series is: 0 1 1 2 3 5 8
Series is: 0 1 1 2 3 5 8 13
Series is: 0 1 1 2 3 5 8 13 21 34 55 89
raja
Published on 04-Feb-2021 10:56:00
Advertisements