Skip to content
Devtoolry

Numbers · beginner

C Program to Print the Fibonacci Series

Print the Fibonacci series in C with a for loop, then with recursion, and see why the recursive version gets slow and how unsigned long long holds 93 terms.

In the Fibonacci series each term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, … The loop version keeps only the last two terms, so it uses almost no memory and takes one step per term.

The program

C
#include <stdio.h>

int main(void) {
    int n = 10;
    unsigned long long a = 0, b = 1;

    printf("First %d terms:", n);
    for (int i = 0; i < n; i++) {
        printf(" %llu", a);
        unsigned long long next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}
Output
First 10 terms: 0 1 1 2 3 5 8 13 21 34

How it works

  1. a and b hold two consecutive terms, starting with 0 and 1.
  2. Each pass prints a, then computes the next term a + b.
  3. a takes the old b and b takes the new term, moving the pair one step forward.
  4. unsigned long long is large enough for the first 94 terms (up to F(93)).

Another way: Recursive version

fib(n) = fib(n - 1) + fib(n - 2) is short but recomputes the same terms many times: fib(30) makes 2,692,537 calls. It is fine for small n and a good recursion exercise.

C
#include <stdio.h>

static long calls = 0;

unsigned long long fib(int n) {
    calls++;
    return n < 2 ? (unsigned long long)n : fib(n - 1) + fib(n - 2);
}

int main(void) {
    for (int i = 0; i < 10; i++)
        printf("%llu ", fib(i));
    printf("\n");
    calls = 0;
    unsigned long long f30 = fib(30);
    printf("fib(30) = %llu after %ld calls\n", f30, calls);
    return 0;
}
Output
0 1 1 2 3 5 8 13 21 34 
fib(30) = 832040 after 2692537 calls

Common mistakes

  • Updating a and b in the wrong order (a = b; b = a + b;), which uses the new a in the second line.
  • Using int, which overflows after F(46) = 1,836,311,903.
  • Using the recursive version for n around 50: it would take minutes.
  • Writing printf("%llu %ld", fib(30), calls): C does not fix the order in which arguments are evaluated, so calls may be read before fib(30) runs (gcc and clang differ here). Store the result in a variable first.

Try it yourself

  • Print all Fibonacci numbers smaller than 1,000.
  • Store the first 50 terms in an array and print every fifth one.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.