Fibonacci Series in C: Iterative, Recursive, and Memoized Code
To print the Fibonacci series in C, start with 0 and 1, then add the last two numbers in a loop. Learn the iterative, recursive, and memoized versions with working code in C, C++, Java, and Python, plus the complexity trade-offs for each.
Say you are in a lab exam and you have written a recursive Fibonacci program in C. It works for n = 10, but when you test n = 45 the screen hangs. You know the series by heart, yet you cannot say why the program is so slow or how to fix it. This post gives you the loop, the recursion and the cached version in C, with the output to check each one against.
To print the Fibonacci series in C, start with 0 and 1, then add the last two numbers in a loop to get the next one. The same idea works in C++, Python and Java. Learn the loop first, then the recursive and memoized versions. For 10 terms, every correct program prints 0 1 1 2 3 5 8 13 21 34, the values listed on Wikipedia's Fibonacci sequence page.
Fibonacci rule and the output to expect
Each term is the sum of the two before it, with F(0)=0 and F(1)=1, so the first terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 (Wikipedia). Written as a formula, F(n) = F(n-1) + F(n-2) for every n above 1. The sequence is named after Leonardo of Pisa, who introduced it to Europe in his book Liber Abaci in 1202, according to the same Wikipedia article.
Keep this table open while you practise. If your program prints a number that is not in it, the bug is in your code, not in the table.
| n | F(n) | n | F(n) |
|---|---|---|---|
| 0 | 0 | 7 | 13 |
| 1 | 1 | 8 | 21 |
| 2 | 1 | 9 | 34 |
| 3 | 2 | 10 | 55 |
| 4 | 3 | 11 | 89 |
| 5 | 5 | 12 | 144 |
| 6 | 8 | Source: Wikipedia, Fibonacci sequence | |
Write the iterative version in C
A loop that keeps only the last two numbers prints the series in one pass and is the version to write first in an interview. This program follows the iterative example in Unstop's C walkthrough:
#include <stdio.h>
int main() {
int n = 10;
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; i++) {
printf("%d ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
0 1 1 2 3 5 8 13 21 34
Here is what each variable does, in plain words:
nis how many terms you want printed.t1is the term you print right now.t2is the term after it, waiting its turn.nextTermis a scratch space for their sum before you shift both values forward.
The loop body runs once per term and does a fixed amount of work each time. That gives O(n) time, as the Unstop article notes. It also uses only three integers of memory, no matter how large n gets.
Port the loop to C++, Java and Python
The loop logic stays identical across languages; only printing syntax and input handling change, along with the types. You can see this in the Java loop versions on BeginnersBook, which use the same "print, add, shift" body as the C program.
Start with C++. This version stops at a value limit, not a term count. It prints every Fibonacci number up to and including n:
#include <iostream>
using namespace std;
int main() {
int n = 34; // largest value to print, not number of terms
int t1 = 0, t2 = 1, nextTerm = t1 + t2;
cout << t1 << ", " << t2;
while (nextTerm <= n) {
cout << ", " << nextTerm;
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
The values match the Wikipedia table. If the interviewer says "print 10 terms", use a counted loop like the C version. This value-limit version would print the wrong amount.
Java needs a class and a main method around the same loop. This version prints a label first, as in the BeginnersBook example, and its output for 7 numbers is Fibonacci Series of 7 numbers:0 1 1 2 3 5 8.
public class JavaExample {
public static void main(String[] args) {
int count = 7, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series of " + count + " numbers:");
for (int i = 1; i <= count; ++i) {
System.out.print(num1 + " ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}
Python is the shortest. A generator, like the one in Vultr's Python guide, hands back one term at a time:
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(*fibonacci(10)) # the first ten terms, space-separated
The one thing that differs in each language:
- C++: printing uses
cout <<, and this version takes a value limit. - Java: use
System.out.print, notprintln, or each term lands on its own line. - Python:
a, b = b, a + bswaps both values at once, so there is no temporary variable.
The four steps that carry over to any language:
Set the starting pair
Put zero in the first variable and one in the second.
Print the current term
Print the first variable, followed by a space or comma.
Compute the sum
Add the two variables to get the term after the next one.
Shift forward
Move the second value into the first and the sum into the second, then loop.
If you ask an AI assistant to port your C loop into a new language, read its version line by line with this checklist for reviewing AI-generated code before you trust it.
Use recursion when the interviewer asks for it
A recursive function mirrors the definition directly, with fibonacci(n) returning n for n of 0 or 1 and the sum of two smaller calls otherwise. In the Unstop recursive example, printing 7 terms gives 0 1 1 2 3 5 8, and the nth-term call fibonacci(6) returns 8.
#include <stdio.h>
int fibonacci(int n) {
if (n == 0 || n == 1)
return n; // base case
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int terms = 7;
for (int i = 0; i < terms; i++)
printf("%d ", fibonacci(i));
printf("\n%d\n", fibonacci(6)); // nth-term form
return 0;
}
The same function in Python and Java:
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
static int fibonacci(int n) {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
The base case is the line that stops the recursion. Delete it, and the function keeps calling itself with smaller and smaller numbers, into the negatives, until the program runs out of stack space. C crashes with a segmentation fault, Java throws StackOverflowError, and Python raises RecursionError.
There is a hidden cost too. To get fibonacci(5), the function computes fibonacci(3) twice and fibonacci(2) three times. Every repeat starts from scratch, and the repeats multiply as n grows.
Memoization stops the repeated work
Saving each result after the first time you compute it turns the slow recursive version into a linear-time one, and Python's functools.lru_cache does the saving for you, as shown in Vultr's Python examples:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # same answer as before
print(*(fibonacci(i) for i in range(10))) # same series as the loop
The function body did not change. Only the decorator line is new, and both outputs match the plain recursive version.
In C or Java there is no decorator, so you build the cache yourself with an array. Here is the C version:
#include <stdio.h>
long long memo[100];
long long fibonacci(int n) {
if (n < 2) return n;
if (memo[n] != 0) return memo[n]; // already computed
memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
return memo[n];
}
int main() {
for (int i = 0; i < 10; i++)
printf("%lld ", fibonacci(i));
return 0;
}
0 1 1 2 3 5 8 13 21 34
The Java version uses the same logic:
public class FibMemo {
static long[] memo = new long[100];
static long fibonacci(int n) {
if (n < 2) return n;
if (memo[n] != 0) return memo[n]; // already computed
memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
return memo[n];
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.print(fibonacci(i) + " ");
}
}
The cache holds one slot per value of n. A slot stays zero until F(n) is computed once, and after that every call just reads it. Zero can mean "not yet computed" because only F(0) equals zero, and the base case returns it before the array is checked. This array holds up to F(99), but long overflows after F(92), so stay below that.
Complexity comparison: iterative, recursive, memoized
Iterative and memoized run in O(n), while plain recursion grows as O(2^n) because the calls form a tree that nearly doubles at each level (the tight bound is about 1.618^n), so it becomes unusable for large n, per the Unstop analysis. Here is the whole drill on one screen:
| Version | Time | Extra memory | When to use | Languages covered, output for n=10 |
|---|---|---|---|---|
| Iterative | O(n) | Three integer variables, constant memory | Your default answer | C, C++ (value limit), Java, Python: F(0) to F(9) |
| Recursive | O(2^n) | Call stack as deep as n | When asked for recursion | C, Python, Java: F(0) to F(9), slower |
| Memoized | O(n) | Cache of n results plus the stack | Follow-up: "make it faster" | Python (lru_cache), Java (array): F(0) to F(9) |
| Complexity: Unstop. Values: Wikipedia. | ||||
Check your output: for n=10, all three versions must print the first ten values from the table at the top of this post, in the same order. If one version differs, that version has the bug.
Common mistakes that cost marks
Most wrong outputs come from four slips: wrong starting values, an off-by-one loop count, a missing base case, and int overflow for large terms. Here is how each one shows up on screen:
- Wrong starting values. Starting with one and one prints
1 1 2 3instead of0 1 1 2 3, which does not match the F(0)=0 definition on Wikipedia. - Off-by-one loop. Writing
i <= nwithistarting at zero prints eleven terms when you asked for ten. Count your output before you submit. - Missing base case. The recursive version never returns and crashes with a stack error.
- Int overflow. A 32-bit
intoverflows after F(46), so a 50-term run prints wrong values, often negative ones, from the 48th term on. Switch tolong longin C and C++, orlongin Java.
Do
- Say the time complexity of each version out loud.
- Ask whether "n" means a term count or a value limit.
- Run the code once with a small n before a large one.
Don't
- Start with recursion unless asked.
- Use
printlnin Java when the output should be on one line. - Skip the base case to "save time".
Open a blank file tonight, close this page, and write the iterative Fibonacci program in C from memory. Run it for 10 terms and check that it prints 0 1 1 2 3 5 8 13 21 34, the series on Wikipedia. Tomorrow, repeat in Java or Python.

