Generating Fibonacci Series | Python, Java, JavaScript

The Fibonacci sequence is a classic mathematical series that transcends programming languages. In this post, we'll delve into the Fibonacci sequence and its implementation in three different programming languages: Python, Java, and JavaScript. By comparing these implementations, we'll highlight the elegance of the Fibonacci sequence and its universality in code.

Fibonacci Sequence

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.

Python implementation

def fibonacci(n):
    fib_series = [0, 1]

    for i in range(2, n):
        next_term = fib_series[i - 1] + fib_series[i - 2]
        fib_series.append(next_term)

    return fib_series

n = int(input("Enter the value of n: "))

if n <= 0:
    print("Please enter a positive integer.")
else:
    fib_series = fibonacci(n)
    print(f"Fibonacci series up to the {n}th term:")
    print(fib_series)
    

Java implementation

class Fibonacci {
    public static void main(String[] args) {
        int n = 10;
        int[] fibSeries = new int[n];
        fibSeries[0] = 0;
        fibSeries[1] = 1;

        for (int i = 2; i < n; i++) {
            fibSeries[i] = fibSeries[i - 1] + fibSeries[i - 2];
        }

        System.out.print("Fibonacci series up to the " + n + "th term: ");
        for (int num : fibSeries) {
            System.out.print(num + " ");
        }
    }
}
    

JavaScript Implementation

function fibonacci(n) {
    var fibSeries = [0, 1];

    for (var i = 2; i < n; i++) {
        var nextTerm = fibSeries[i - 1] + fibSeries[i - 2];
        fibSeries.push(nextTerm);
    }

    return fibSeries;
}

var n = 10;
var fibSeries = fibonacci(n);
console.log(`Fibonacci series up to the ${n}th term:`, fibSeries);
    

Conclusion

The Fibonacci sequence is a timeless mathematical concept that finds its place in various programming languages. By exploring its implementations in Python, Java, and JavaScript, we've witnessed how this sequence elegantly unfolds across languages, emphasizing the power of mathematics in coding.




Post a Comment

1 Comments


  1. VmapU Consultancy is the best Overseas Education consultant as well as Immigration and Visa Consultant, in Hyderabad.

    We are a helping hand on your journey to becoming an international student and are professionals equipped with specialized knowledge about courses offered by universities in various countries.

    Our aim is to guide students through the intricacies of the admission process, visa application procedures, and other formalities associated with pursuing education abroad.

    ReplyDelete