Go Program to Calculate the Fibonacci Series

1. Introduction

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones. Often starting with 0 and 1, it has applications in various domains, from computer algorithms to theoretical mathematics. In this blog post, we will learn how to design a Go program that generates the Fibonacci series for a given length.

2. Program Overview

Our Go program is designed to:

1. Prompt the user to specify the length of the Fibonacci series.

2. Compute the Fibonacci series up to the given length.

3. Display the generated Fibonacci series to the user.

3. Code Program

// Declaring the main package to indicate the commencement of our Go application.
package main

// We incorporate the fmt package to handle input and output tasks.
import "fmt"

// Function to generate Fibonacci series up to a specified length.
func fibonacci(length int) []int {
    sequence := make([]int, length)
    
    for i := range sequence {
        if i == 0 {
            sequence[i] = 0
        } else if i == 1 {
            sequence[i] = 1
        } else {
            sequence[i] = sequence[i-1] + sequence[i-2]
        }
    }
    return sequence
}

// Our program's execution starts from the main function.
func main() {
    // Declaring an int variable to store the user-specified length of the series.
    var length int

    // Requesting the user to provide the length for the Fibonacci series.
    fmt.Print("Enter the length of the Fibonacci series: ")
    fmt.Scan(&length)

    // Displaying the generated Fibonacci series to the user.
    fmt.Println("The Fibonacci series of length", length, "is:", fibonacci(length))
}

Output:

Should the user input the number 5, the program's output would be:
The Fibonacci series of length 5 is: [0 1 1 2 3]

4. Step By Step Explanation

1. Package and Import Statements: We begin with the package main statement, marking the program's starting point. For performing I/O operations, the fmt package is imported.

2. Fibonacci Function: The fibonacci function is designed to generate the series. An integer slice is initialized to store the series. For each position in the slice, if it's the 0th or 1st index, we populate it with 0 or 1, respectively. For all other positions, the value is the sum of the previous two numbers.

3. Variable Declaration: Using the var keyword, we introduce an integer variable named length that will retain the user-defined length for the series.

4. Collecting User Input: We use fmt.Print to present a prompt, and the input is captured with fmt.Scan.

5. Computing and Presenting the Series: The fibonacci function is invoked with the provided length, and the resultant series is showcased using fmt.Println.

Comments