The Fibonacci series in C is a sequence of numbers where every number is the sum of the two numbers before it, starting with 0 and 1 (0, 1, 1, 2, 3, 5, 8, 13, 21…). In C programming, you generate this series using a loop (for or while), recursion, or an array — the loop-based approach is the simplest for beginners, while recursion is used to teach function calls and problem decomposition. Below, you’ll find complete, tested C programs for every method, along with the algorithm, output, complexity analysis, and common mistakes to avoid.
If you’re just starting out with C, the Fibonacci series is one of the first logic-building programs you’ll write after loops and conditionals — right alongside topics like arrays, loops, and functions that form the foundation of the language. It’s also a favorite in college lab exams, coding interviews, and placement tests because it tests whether you actually understand iteration and recursion, not just syntax.
This guide covers every way to write a Fibonacci program in C — using loops, recursion, arrays, and functions — with working code, sample output, and a breakdown of what’s happening at each step.
What is the Fibonacci Series?
The Fibonacci series (also called the Fibonacci sequence) is a series of numbers in which each number is the sum of the two preceding numbers. The sequence typically starts with 0 and 1:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Mathematically, the Fibonacci sequence is defined by the recurrence relation:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2), for n > 1
This means to find any term, you simply add the two terms before it. The sequence is named after the Italian mathematician Leonardo of Pisa, known as Fibonacci, who introduced it to Western mathematics in his 1202 book Liber Abaci, although the sequence had been described earlier in Indian mathematics.
The Fibonacci series shows up far beyond textbooks — it appears in the branching of trees, the arrangement of leaves on a stem, the spiral of a nautilus shell, and even in financial market analysis. In computer science, it’s a classic example used to teach:
- Iterative logic (loops)
- Recursive thinking (a function calling itself)
- Time and space complexity trade-offs
- Dynamic programming and memoization
That’s exactly why it’s such a popular exercise in every C programming course — it’s simple enough for a first-year student to understand, yet rich enough to demonstrate multiple programming paradigms in a single problem.
Fibonacci Series Example
Let’s trace through the first ten terms manually so the logic is crystal clear before we write any code.
| Term (n) | Calculation | Value |
|---|---|---|
| F(0) | — | 0 |
| F(1) | — | 1 |
| F(2) | 0 + 1 | 1 |
| F(3) | 1 + 1 | 2 |
| F(4) | 1 + 2 | 3 |
| F(5) | 2 + 3 | 5 |
| F(6) | 3 + 5 | 8 |
| F(7) | 5 + 8 | 13 |
| F(8) | 8 + 13 | 21 |
| F(9) | 13 + 21 | 34 |
So the first 10 terms of the Fibonacci series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Notice the pattern: every term after the first two is simply the sum of its two predecessors. This “sum of the last two” rule is the entire logic you need to translate into C code.
Fibonacci Series Program in C
Let’s start with the most common and beginner-friendly version — printing the Fibonacci series up to n terms using a for loop.
C Program to Print Fibonacci Series
#include <stdio.h>
int main() {
int n, i;
int t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i <= n; ++i) {
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
This program asks the user how many terms they want, then prints that many terms of the series, separated by commas.
Output
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
How the Program Works
Let’s break the program down line by line so the logic is completely clear:
- Variable initialization:
t1 = 0andt2 = 1represent the first two terms of the series.nextTermwill store each new number we calculate. - Taking input: The program asks the user for
n, the number of terms they want printed. - The loop: The
forloop runs fromi = 1toi = n. On every iteration:- It first prints the current value of
t1(the “current” Fibonacci number). - It calculates
nextTerm = t1 + t2(the sum of the last two terms). - It then shifts the window forward:
t1becomes the oldt2, andt2becomes the newly calculatednextTerm.
- It first prints the current value of
- Repeat: This shifting process is what makes the loop “remember” the last two numbers without needing to store the entire sequence.
This technique — keeping only the last two values and updating them each time — is called the iterative (bottom-up) approach, and it’s the most memory-efficient way to generate the series. If you’re also exploring iterative logic in other classic problems, the Bubble Sort program in C is a good next stop — it uses the same nested-loop discipline you’ll rely on throughout C programming.
Algorithm to Generate Fibonacci Series in C
Before coding, it helps to write the algorithm in plain steps. Here’s the algorithm for the iterative approach:
Step 1: Start
Step 2: Declare variables n, i, t1, t2, nextTerm
Step 3: Initialize t1 = 0, t2 = 1
Step 4: Read the number of terms (n) from the user
Step 5: Print t1 (the current term)
Step 6: Repeat steps 7 to 9 for i = 1 to n
Step 7: Calculate nextTerm = t1 + t2
Step 8: Update t1 = t2 and t2 = nextTerm
Step 9: Print t1
Step 10: Stop
This algorithm forms the blueprint for every loop-based Fibonacci program, whether you implement it with a for loop, a while loop, or even a do-while loop. Once you’re comfortable converting an algorithm like this into working code, you’ll find it much easier to design your own algorithms for other numeric pattern problems.
Fibonacci Series Using for Loop in C
The for loop is the most natural choice here because we already know exactly how many terms we need to print. Here’s a clean, standalone version:
#include <stdio.h>
int main() {
int n = 10;
int t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series up to %d terms:\n", n);
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf("\n");
return 0;
}
Output:
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34
Why this works well: The for loop keeps the initialization, condition, and increment all in one line, making the code compact and easy to read. It’s the preferred choice in interviews and lab exams because the loop bounds are explicit and there’s less risk of an infinite loop compared to a while loop with a forgotten update statement.
Fibonacci Series Using while Loop in C
If you’d rather control the loop condition manually — useful when the number of terms depends on a condition rather than a fixed count — a while loop works just as well.
#include <stdio.h>
int main() {
int n, i = 1;
int t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
while (i <= n) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
i++;
}
return 0;
}
Output:
Enter the number of terms: 8
Fibonacci Series: 0 1 1 2 3 5 8 13
The logic is identical to the for loop version — the only difference is where the initialization (i = 1), condition (i <= n), and increment (i++) are written. A common beginner mistake here is forgetting to write i++ inside the loop body, which causes an infinite loop since the condition i <= n never becomes false. Always double-check your increment statement when using while loops.
Fibonacci Series Using Recursion in C
Recursion offers a more elegant, mathematical way to express the Fibonacci relationship — because the recursive definition of Fibonacci (F(n) = F(n-1) + F(n-2)) maps directly onto a recursive function.
Recursive Fibonacci Function
#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
return 0;
}
Output:
Enter the number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
How Recursion Works
The fibonacci() function has two essential parts:
- Base case:
if (n == 0) return 0;andelse if (n == 1) return 1;— these stop the recursion. Without a base case, the function would call itself forever and crash with a stack overflow. - Recursive case:
return fibonacci(n - 1) + fibonacci(n - 2);— this breaks the problem into two smaller sub-problems and combines their results.
To understand this visually, trace fibonacci(4):
fibonacci(4)
= fibonacci(3) + fibonacci(2)
= [fibonacci(2) + fibonacci(1)] + [fibonacci(1) + fibonacci(0)]
= [(fibonacci(1) + fibonacci(0)) + 1] + [1 + 0]
= [(1 + 0) + 1] + [1 + 0]
= 2 + 1
= 3
Notice that fibonacci(2) and fibonacci(1) get calculated multiple times. This repeated calculation is the biggest downside of plain recursion — it’s elegant to read, but computationally wasteful for larger values of n. This is the same trade-off you’ll encounter in other recursive problems taught early in Data Structures and Algorithms, where recursion, stacks, and function call overhead are core topics.
Fibonacci Series Using Array in C
Storing the series in an array is useful when you need to reuse the generated numbers later in your program — for example, to search for a specific term, reverse the sequence, or pass it to another function.
#include <stdio.h>
int main() {
int n, i;
printf("Enter the number of terms: ");
scanf("%d", &n);
int fib[n];
fib[0] = 0;
if (n > 1) {
fib[1] = 1;
}
for (i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
printf("Fibonacci Series: ");
for (i = 0; i < n; i++) {
printf("%d ", fib[i]);
}
return 0;
}
Output:
Enter the number of terms: 9
Fibonacci Series: 0 1 1 2 3 5 8 13 21
Here, fib[] stores every term as it’s generated, so the entire series remains available in memory for later use — unlike the loop-only approach, which discards each number after printing it. This trade-off between speed and memory is a good introduction to why data structures matter, a theme you’ll see repeated throughout array and string-based problems in C.
Fibonacci Series Without Recursion in C
“Without recursion” simply means using iteration (loops) instead of a function calling itself. All the for loop, while loop, and array-based programs above are non-recursive approaches. This method is generally preferred in production code and performance-sensitive programs because it avoids the overhead of repeated function calls and the risk of stack overflow for large n.
Here’s a consolidated, non-recursive version that also demonstrates good practice — separating logic into its own function while keeping it purely iterative:
#include <stdio.h>
void printFibonacciIterative(int n) {
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
printFibonacciIterative(n);
return 0;
}
Output:
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
The key advantage: this version runs in linear time and uses constant extra memory, making it the go-to choice whenever performance matters — such as calculating large Fibonacci terms in coding assessments or system-level programs.
Find the nth Fibonacci Number in C
Sometimes you don’t need the entire series — you just need a single term, like “What is the 15th Fibonacci number?” Here’s an efficient iterative solution:
#include <stdio.h>
int nthFibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
if (n == 0) return t1;
for (int i = 2; i <= n; i++) {
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return t2;
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("The %dth Fibonacci number is: %d\n", n, nthFibonacci(n));
return 0;
}
Output:
Enter the value of n: 15
The 15th Fibonacci number is: 610
This approach runs in O(n) time and O(1) space — far more efficient than calling the plain recursive function repeatedly, which would take exponential time for the same value of n. If you ever need extremely large Fibonacci numbers (say, the 1000th term), you’d also need to switch from int to a data type like long long or implement big-number arithmetic, since standard integer types overflow quickly as Fibonacci numbers grow.
Fibonacci Series Using Function in C
Wrapping your Fibonacci logic inside a function makes your code reusable, testable, and easier to plug into larger programs — a habit worth building early, since real-world C projects are built almost entirely out of well-structured functions.
#include <stdio.h>
void generateFibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
generateFibonacci(n);
return 0;
}
Output:
Enter the number of terms: 12
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89
Separating the Fibonacci logic into generateFibonacci() means you can call this function from anywhere in a larger program — for instance, inside a menu-driven application that also includes other classic beginner programs like prime number checks, Armstrong numbers, or sorting algorithms. This modular style is exactly what you’ll practice while working through a set of beginner C programming projects.
Fibonacci Programs in C: Methods Compared
Different situations call for different Fibonacci implementations. Here’s a side-by-side comparison to help you choose the right one:
| Method | Best For | Time Complexity | Space Complexity | Key Limitation |
|---|---|---|---|---|
for loop (iterative) |
General-purpose, fixed number of terms | O(n) | O(1) | None significant |
while loop (iterative) |
Condition-based termination | O(n) | O(1) | Risk of infinite loop if increment is missed |
| Recursion | Teaching recursion, small n |
O(2^n) | O(n) (call stack) | Extremely slow for large n; repeated calculations |
| Array-based | When you need to reuse or search the series later | O(n) | O(n) | Uses more memory than plain loops |
| Function-based (modular) | Reusable, larger programs | O(n) | O(1) | Requires slightly more code structure |
| nth term (direct) | When only one specific term is needed | O(n) | O(1) | Doesn’t store or print the full series |
For most practical use cases and exams, the iterative for loop approach is the recommended default — it’s fast, simple, and easy to explain. Recursion is worth learning for the concept itself, and because interviewers frequently ask you to first write the recursive version and then optimize it — which brings us to memoization.
A quick note on optimized recursion (memoization): You can fix the recursion’s repeated-work problem by storing already-computed results in an array and reusing them instead of recalculating:
#include <stdio.h>
int memo[50];
int fibMemo(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
if (memo[n] != -1) return memo[n];
memo[n] = fibMemo(n - 1) + fibMemo(n - 2);
return memo[n];
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (int i = 0; i < 50; i++) memo[i] = -1;
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibMemo(i));
}
return 0;
}
This brings recursion’s time complexity down from exponential O(2^n) to linear O(n), at the cost of O(n) extra space for the memo[] array. This is your first real taste of dynamic programming — a technique you’ll use extensively in more advanced DSA problems and projects.
Common Mistakes in Fibonacci Programs in C
Even though the Fibonacci program is simple, beginners run into the same handful of errors repeatedly. Watch out for these:
- Forgetting to initialize
t1andt2correctly. The series must start with0and1. If you initialize both to0, or1and0in the wrong order, your output will be incorrect from the start. - Off-by-one errors in loop conditions. Using
i < ninstead ofi <= n(or vice versa) will print one term too few or too many. Always trace through a small example (liken = 5) by hand to confirm the loop prints exactly the right count. - Missing base cases in recursion. If you forget
if (n == 0) return 0;orelse if (n == 1) return 1;, the recursive function will never terminate and will crash with a stack overflow error. - Integer overflow for large
n. Since Fibonacci numbers grow exponentially, a regularint(typically 32-bit) overflows around the 47th term. If you need larger terms, switch tolong long intor use an array-based big-integer approach. - Confusing 0-indexed and 1-indexed series. Some problems ask for “the first 10 Fibonacci numbers starting from 1,” while others start counting from 0. Always clarify (or explicitly define in your code comments) whether your series begins at
F(0)orF(1). - Using plain recursion for large
nin performance-critical code. As shown in the comparison table, uncontrolled recursion has exponential time complexity. For anything beyond small teaching examples, use iteration or memoization instead. - Not updating loop variables in a
whileloop. Forgettingi++(or forgetting to updatet1andt2) causes infinite loops — a very common mistake for students moving fromforloops towhileloops.
Avoiding these pitfalls will not only make your Fibonacci program correct but will also build habits that carry over to every other loop- and recursion-based problem you write in C.
Time and Space Complexity
Understanding complexity is what separates “a program that works” from “a program that works efficiently” — and Fibonacci is one of the best examples to learn this on, because the same problem can range from exponential to linear time depending on your implementation.
| Approach | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
| Iterative (loop-based) | O(n) | O(1) | Each term is calculated once in a single pass; only two variables are stored at a time. |
| Plain recursion | O(2^n) | O(n) | The recursion tree branches into two calls at every step, causing massive repeated work; O(n) space comes from the call stack depth. |
| Recursion with memoization | O(n) | O(n) | Each sub-problem is solved once and cached, eliminating repeated calculations, at the cost of extra memory for the cache. |
| Array-based | O(n) | O(n) | Linear time to fill the array, but the array itself uses O(n) space to store every term. |
Why this matters: In a classroom setting, the difference between O(n) and O(2^n) might seem abstract. But try running the plain recursive version with n = 40 versus n = 10 — the exponential version will take visibly longer (potentially several seconds), while the iterative version handles n = 40 almost instantly. This hands-on demonstration is exactly why Fibonacci is such a popular teaching tool for complexity analysis, alongside sorting algorithms like Bubble Sort, which is commonly used to illustrate O(n²) time complexity in the same way.
FAQs
What is the Fibonacci series in C?
The Fibonacci series in C refers to a program that generates the Fibonacci sequence — a series of numbers where each number is the sum of the two before it, starting from 0 and 1 — using C programming constructs like loops, recursion, or arrays. It’s typically implemented using variables to track the current and previous terms, then printed using printf() inside a loop or recursive function.
How do you write a Fibonacci series program in C?
To write a Fibonacci series program in C, initialize two variables (commonly t1 = 0 and t2 = 1) to represent the first two terms. Then use a loop to repeatedly print the current term, calculate the next term as the sum of the previous two, and shift the variables forward. Ask the user for the number of terms using scanf(), and print each term inside the loop using printf(). The complete working code is provided in the “C Program to Print Fibonacci Series” section above.
How do you print Fibonacci series using a for loop?
Use a for loop that runs from 1 to n (the number of terms). Inside the loop, print the current value of t1, calculate nextTerm = t1 + t2, then update t1 = t2 and t2 = nextTerm. This shifts the “window” of the last two numbers forward on each iteration. See the complete “Fibonacci Series Using for Loop in C” section above for the full code and output.
How do you generate Fibonacci series using recursion?
Define a recursive function, such as fibonacci(int n), with two base cases: return 0 when n == 0, and return 1 when n == 1. For all other values, return fibonacci(n - 1) + fibonacci(n - 2). Call this function inside a loop in main() to print each term of the series. Note that plain recursion has exponential time complexity, so it’s best suited for small values of n or for learning purposes — use memoization or iteration for larger inputs.
What is the Fibonacci formula?
The Fibonacci formula (recurrence relation) is:
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2), for n > 1
There’s also a closed-form expression called Binet’s Formula, which calculates the nth Fibonacci number directly using the golden ratio (φ ≈ 1.618) without needing to compute the preceding terms:
F(n) = (φⁿ - ψⁿ) / √5
where φ = (1 + √5) / 2 and ψ = (1 - √5) / 2. In practice, this formula is rarely used in C programs because it relies on floating-point arithmetic, which can introduce rounding errors for larger values of n. The iterative or recursive approaches remain the standard choice for programming exercises.
How do you find the nth Fibonacci number?
To find the nth Fibonacci number in C, use an iterative loop that tracks only the last two computed values (t1 and t2) instead of generating and storing the entire series. Loop from 2 to n, updating t1 and t2 on each iteration, and return the final value of t2. This runs in O(n) time and O(1) space, making it far more efficient than plain recursion for larger values of n. The complete code is available in the “Find the nth Fibonacci Number in C” section above.
Practice Programs Based on Fibonacci Series
Once you’re comfortable with the standard Fibonacci program, try these variations to deepen your understanding of loops, recursion, and functions in C:
- Print the Fibonacci series in reverse order — generate the series first (using an array), then print it from the last term to the first.
- Check whether a given number is a Fibonacci number — write a function that verifies if a user-input number appears anywhere in the Fibonacci sequence.
- Print only the even Fibonacci numbers up to n terms, and separately, only the odd ones.
- Calculate the sum of the first n Fibonacci numbers using both loop-based and recursive approaches.
- Print the Fibonacci series using a
do-whileloop instead offororwhile, to practice all three loop types in C. - Implement the Fibonacci series using pointers — pass
t1andt2by reference to a function that updates them. - Write a memoized (dynamic programming) version of the recursive Fibonacci function and compare its execution time against plain recursion for
n = 35. - Generate Fibonacci numbers larger than the
intrange usinglong long intor an array-based big-number technique. - Combine Fibonacci logic with file handling — write the generated series to a text file instead of printing it to the console.
- Build a menu-driven C program that lets the user choose between the iterative, recursive, and array-based Fibonacci implementations, reinforcing the modular, function-based coding style used throughout this guide.
Practicing these variations is one of the best ways to move from “I can copy a Fibonacci program” to “I understand loops, recursion, and functions well enough to solve new problems on my own” — which is exactly the kind of hands-on, problem-solving skill that Codegnan’s C programming training is built around. And once you’re confident with these fundamentals, you’ll be well-prepared to explore data structures, algorithms, and other core C career skills that build directly on what you’ve learned here.




