#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Fibonacci Series Using Recursion in C with Code

Understanding number series is a crucial stepping stone in the world of programming. Among these, the Fibonacci series stands out for its elegance, mathematical importance, and its frequent appearance in technical interviews. In this guide, we’ll take a closer look at how to implement the Fibonacci series using recursion in C, explore how it works, and explore both the theoretical and practical sides of it.

Blogging Illustration

The Fibonacci series is the most common first example of recursion in C because its mathematical definition is already recursive. This page gives a complete, compiling C program, traces exactly what the computer does when it runs, explains why the simple version becomes slow, and shows two faster versions.

What is the Fibonacci series?

Each term is the sum of the two terms before it. The series starts with 0 and 1:

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

Written as a rule:

F(0) = 0
F(1) = 1
F(n) = F(n - 1) + F(n - 2)   for n >= 2

A recursive function has the same two parts as this rule: base cases that return an answer directly (F(0) and F(1)), and a recursive case that calls the same function on smaller inputs. If recursion itself is new to you, this beginner guide to recursion in C covers it with simpler examples first.

Fibonacci series program in C using recursion

#include <stdio.h>

/* Returns the nth Fibonacci number: F(0) = 0, F(1) = 1 */
int fibonacci(int n) {
    if (n == 0)
        return 0;                                   /* base case 1 */
    if (n == 1)
        return 1;                                   /* base case 2 */
    return fibonacci(n - 1) + fibonacci(n - 2);     /* recursive case */
}

int main(void) {
    int n;
    printf("Enter the number of terms: ");
    if (scanf("%d", &n) != 1 || n < 0) {
        printf("Please enter a non-negative whole number.\n");
        return 1;
    }
    printf("Fibonacci Series: ");
    for (int i = 0; i < n; i++)
        printf("%d ", fibonacci(i));
    printf("\n");
    return 0;
}

Output:

Enter the number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

How the program works

  • fibonacci(int n) returns the nth term. For 0 and 1 it returns immediately; for anything larger it returns the sum of the two previous terms, each found by a recursive call.
  • main() reads how many terms to print and calls fibonacci(i) for i = 0, 1, 2, ... n−1.
  • The scanf check rejects letters and negative numbers, so the program never calls fibonacci with a value that has no base case.

Dry run: what happens when you call fibonacci(4)

Each call that is not a base case splits into two more calls. The call tree for fibonacci(4) is:

fibonacci(4)
├── fibonacci(3)
│   ├── fibonacci(2)
│   │   ├── fibonacci(1) → 1
│   │   └── fibonacci(0) → 0
│   │   returns 1 + 0 = 1
│   └── fibonacci(1) → 1
│   returns 1 + 1 = 2
└── fibonacci(2)
    ├── fibonacci(1) → 1
    └── fibonacci(0) → 0
    returns 1 + 0 = 1
returns 2 + 1 = 3

Count the boxes: fibonacci(4) needs 9 calls, and fibonacci(2) is computed twice. The calls run depth-first: C finishes the whole left branch, fibonacci(3), before it starts the right branch, fibonacci(2). At any moment the stack holds at most n frames (here 4), one for each level of the tree that is still waiting for an answer.

Time and space complexity

The number of calls needed to compute F(n) with this function is exactly 2·F(n+1) − 1:

nF(n)Calls made by fibonacci(n)
439
5515
1055177
206,76521,891
30832,0402,692,537
40102,334,155331,160,281
  • Time: the call count grows by a factor of about 1.618 (the golden ratio φ) each time n goes up by 1. This is written O(φn), and textbooks often use the simpler upper bound O(2n). Around n = 40 the delay becomes noticeable on a normal laptop.
  • Space: O(n), because the deepest chain of waiting calls is n frames long.
  • Printing the series: the main() above calls fibonacci(i) once per term, so it repeats all the earlier work for every new term. That is fine for 10 or 20 terms, wasteful for 40.

Print the series with recursion in O(n)

If the goal is to print the series (not to find one term), carry the last two terms as parameters. Each call prints one term and makes only one recursive call:

#include <stdio.h>

/* Prints 'count' terms; a and b are the current pair of terms */
void printFib(int a, int b, int count) {
    if (count == 0)
        return;                      /* base case: nothing left to print */
    printf("%d ", a);
    printFib(b, a + b, count - 1);   /* shift the pair one step forward */
}

int main(void) {
    printf("First 10 terms: ");
    printFib(0, 1, 10);
    printf("\n");
    return 0;
}

Output:

First 10 terms: 0 1 1 2 3 5 8 13 21 34

This version makes n + 1 calls in total, so it runs in O(n) time with O(n) stack space. The recursive call is the last thing the function does (a tail call), and optimising compilers such as GCC at -O2 can turn it into a loop, though the C standard does not require that.

Faster recursion: memoisation

The slow version is slow only because it recomputes the same values. Storing each answer the first time it is computed (memoisation) removes the repeats:

#include <stdio.h>

long long memo[93];   /* F(92) is the largest term that fits in a signed 64-bit long long */

long long fib(int n) {
    if (n <= 1)
        return n;
    if (memo[n] != 0)
        return memo[n];                       /* already computed: reuse it */
    return memo[n] = fib(n - 1) + fib(n - 2);
}

int main(void) {
    printf("F(10) = %lld\n", fib(10));
    printf("F(50) = %lld\n", fib(50));
    printf("F(90) = %lld\n", fib(90));
    return 0;
}

Output:

F(10) = 55
F(50) = 12586269025
F(90) = 2880067194370816120

Each F(k) is now computed once, so the time drops to O(n). The global array starts filled with zeros, which works as "not computed yet" because only F(0) is actually 0 and that case is handled by the base case. This idea, solving each subproblem once and reusing it, is the core of dynamic programming.

Iterative version for comparison

#include <stdio.h>

int main(void) {
    int n = 10;
    long long a = 0, b = 1;
    for (int i = 0; i < n; i++) {
        printf("%lld ", a);
        long long next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}

Output:

0 1 1 2 3 5 8 13 21 34
ApproachTimeExtra spaceBest for
Plain recursionO(φn), about O(2n)O(n) stackLearning recursion, small n
Recursion carrying two termsO(n)O(n) stackPrinting the series recursively
Memoised recursionO(n)O(n) array + stackMany lookups of different terms
LoopO(n)O(1)Production code

Common mistakes

  • Missing a base case. With only if (n == 0) return 0;, the call fibonacci(1) goes to fibonacci(0) and fibonacci(−1), and the second branch never stops.
  • Off-by-one in the loop. for (i = 1; i <= n; i++) skips the first term 0. Decide whether your series starts at F(0) or F(1) and say so in the output.
  • Integer overflow. int is safe only up to F(46). Use long long and %lld for larger terms (up to F(92)).
  • Forgetting return on the recursive line. Writing fibonacci(n - 1) + fibonacci(n - 2); without return compiles with a warning but returns garbage.
  • Using plain recursion for big n. fibonacci(50) would need more than 40 billion calls. Use the memoised or iterative version.

The same pattern of base case plus smaller subproblem appears in factorial using recursion in C, in tree traversals, and in graph search such as depth-first search. If you also write C++, the Fibonacci series in C++ with loops and recursion shows the same ideas in that language. For a wider look at how recursion is used on data structures, see recursion in data structures.

Frequently asked questions

What are the base cases in recursive Fibonacci?

F(0) = 0 and F(1) = 1. Every recursive call eventually reaches one of these two, which stops the recursion. If either is missing, fibonacci(1) would call fibonacci(-1) and the program would recurse until the stack overflows.

What is the time complexity of Fibonacci using recursion?

The plain recursive version makes 2·F(n+1) − 1 calls to compute F(n), which grows about 1.618 times with each step of n. It is usually written as O(2n) (a safe upper bound) or more precisely O(φn). The extra space is O(n) for the call stack.

Why does my Fibonacci program print negative numbers?

The value overflowed. A 32-bit int holds values up to 2,147,483,647, so F(46) = 1,836,311,903 is the last term that fits; F(47) does not. Use long long, which holds terms up to F(92).

Is recursion or iteration better for the Fibonacci series in C?

For real programs, the loop is better: O(n) time and O(1) memory. The recursive version is mainly used to learn how recursion, base cases and the call stack work. Memoisation keeps the recursive shape while bringing the time down to O(n).

Recursion, memoisation and complexity analysis are covered with practice problems in Uncodemy's C with Data Structures and Algorithms course.

Placed Students

Our Clients

Partners