Fibonacci Series in C, Python, C++, Java with Code Examples

Fibonacci Series Explained with Code in C, Python, C++, and Java

Introduction

The Fibonacci Series is one of the most famous mathematical sequences. Each number is the sum of the two preceding ones, starting from 0 and 1.

The series goes like this:

0, 1, 1, 2, 3, 5, 8, 13, 21, ...

The Fibonacci series is widely used in mathematics, computer science, dynamic programming, and interview questions.


Formula of Fibonacci Series

The nth Fibonacci number can be defined as:

F(n) = F(n-1) + F(n-2)  
F(0) = 0, F(1) = 1

Fibonacci in C

#include <stdio.h>

int main() {
    int n, first = 0, second = 1, next;
    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");
    for (int i = 0; i < n; i++) {
        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        printf("%d ", next);
    }
    return 0;
}

Fibonacci in Python

def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        print(a, end=" ")
        a, b = b, a + b

n = int(input("Enter number of terms: "))
print("Fibonacci Series:")
fibonacci(n)

Fibonacci in C++

#include <iostream>
using namespace std;

int main() {
    int n, first = 0, second = 1, next;
    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";
    for (int i = 0; i < n; i++) {
        if (i <= 1)
            next = i;
        else {
            next = first + second;
            first = second;
            second = next;
        }
        cout << next << " ";
    }
    return 0;
}

Fibonacci in Java

import java.util.Scanner;

public class Fibonacci {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of terms: ");
        int n = sc.nextInt();
        
        int first = 0, second = 1, next;
        
        System.out.print("Fibonacci Series: ");
        for (int i = 0; i < n; i++) {
            if (i <= 1)
                next = i;
            else {
                next = first + second;
                first = second;
                second = next;
            }
            System.out.print(next + " ");
        }
    }
}

Applications of Fibonacci Series

  • Algorithm Design (Dynamic Programming, Recursion)
  • Computer Graphics & Art (Golden Ratio, Spirals)
  • Nature (Flower petals, leaf arrangements)
  • Stock Market Analysis (Fibonacci retracement levels)

Key Takeaway:
The Fibonacci series is not just a mathematical curiosity but also an essential part of programming, algorithms, and real-life applications. Mastering it will strengthen your logic building and problem-solving skills, especially for coding interviews.

Scroll to Top