Fibonacci Series in C: How to Print Fibonacci Series in C (Iterative & Recursive)

The Fibonacci Series program in C is one of the best programs to practice loops, integer boundaries and recursion. If you want to know how to print fibonacci series in c efficiently, then you can either have the constant memory iteration or a teaching example of recursion. In an iterative loop, you start the first two terms with 0 and 1, print each term and compute the next term in O(n) time and O(1) space as the sum of the previous two numbers. If you simply use unsigned long long, you can safely compute the 93rd Fibonacci number without integer overflow, but the naïve recursive solution has exponential O(2^n) time because it keeps recomputing the same subproblems; memoizing with the help of an array increases the time to linear O(n).

### Fibonacci Series in C: Iterative, Recursive & Memoized Programs

The Fibonacci Series program in C is one of the best programs to practice loops, integer boundaries and recursion. If you want to know how to print fibonacci series in c efficiently, then you can either have the constant memory iteration or a teaching example of recursion. In an iterative loop, you start the first two terms with 0 and 1, print each term and compute the next term in O(n) time and O(1) space as the sum of the previous two numbers. If you simply use unsigned long long, you can safely compute the 93rd Fibonacci number without integer overflow, but the naïve recursive solution has exponential O(2^n) time because it keeps recomputing the same subproblems; memoizing with the help of an array increases the time to linear O(n).

Interactive Runnable C Implementation

#include <stdio.h>

int main(void) {
    int n = 10;
    unsigned long long a = 0ULL, b = 1ULL;
    printf("Fibonacci series in C (%d terms): ", n);
    for (int i = 0; i < n; ++i) {
        printf("%llu%s", a, (i + 1 < n) ? " " : "\n");
        unsigned long long next = a + b;
        a = b;
        b = next;
    }
    return 0;
}

Open example in compiler

Expected Output

Fibonacci series in C (10 terms): 0 1 1 2 3 5 8 13 21 34