Fibonacci Series up to N Value in C, C++, Java and Python
Print all Fibonacci numbers ≤ n using iterative, recursive, and memoization approaches. Full working code in C, C++, Java, and Python.
Every Fibonacci number up to a given limit can be printed with two variables and a while loop: O(n) time, no extra array needed.
That is the entire story for placement-round coding questions on this topic. The sections below back it up with traces, code in four languages, and two slower alternatives that are worth understanding for theory rounds and system-design discussions.
How the Fibonacci series works
The Fibonacci sequence is defined by a simple recurrence: each term is the sum of the two terms before it, with the first two terms fixed at 0 and 1. The sequence is documented in full at Wikipedia’s Fibonacci entry and indexed as OEIS A000045.
In code notation:
F(0) = 0F(1) = 1F(k) = F(k-1) + F(k-2)for k ≥ 2
The “Fibonacci series up to n” problem asks for all terms whose value does not exceed n, not the first n terms. That is a common point of confusion in coding tests.
Trace for n=20, step by step:
- Start: a=0, b=1
- Print 0. New pair: a=1, b=1.
- Print 1. New pair: a=1, b=2.
- Print 1. New pair: a=2, b=3.
- Print 2. New pair: a=3, b=5.
- Print 3. New pair: a=5, b=8.
- Print 5. New pair: a=8, b=13.
- Print 8. New pair: a=13, b=21.
- Print 13. New pair: a=21, b=34.
- Next value 21 exceeds 20. Stop.
Output: 0 1 1 2 3 5 8 13
Iterative approach: O(n) time, O(1) space
Two variables track the current and next term. On each loop iteration, print the current term, compute the sum, and shift the pair forward. No array, no stack, no recursion.
This is the approach interviewers expect. It handles large values of n without stack-overflow risk and runs in linear time.
C
#include <stdio.h>
int main() {
int n, a = 0, b = 1, temp;
printf("Enter limit: ");
scanf("%d", &n);
printf("Fibonacci series up to %d: ", n);
while (a <= n) {
printf("%d ", a);
temp = a + b;
a = b;
b = temp;
}
printf("\n");
return 0;
}
C++
#include <iostream>
using namespace std;
int main() {
int n, a = 0, b = 1, temp;
cout << "Enter limit: ";
cin >> n;
cout << "Fibonacci series up to " << n << ": ";
while (a <= n) {
cout << a << " ";
temp = a + b;
a = b;
b = temp;
}
cout << endl;
return 0;
}
Java
import java.util.Scanner;
public class FibonacciUpto {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter limit: ");
int n = sc.nextInt();
int a = 0, b = 1, temp;
System.out.print("Fibonacci series up to " + n + ": ");
while (a <= n) {
System.out.print(a + " ");
temp = a + b;
a = b;
b = temp;
}
System.out.println();
}
}
Python
n = int(input("Enter limit: "))
a, b = 0, 1
print(f"Fibonacci series up to {n}:", end=" ")
while a <= n:
print(a, end=" ")
a, b = b, a + b
print()
Python’s tuple assignment (a, b = b, a + b) handles the variable swap in one line without a temporary variable. The logic is identical to the C and Java versions.
Recursive approach: the n-th term function
The textbook recursive definition of Fibonacci is fib(k) = fib(k-1) + fib(k-2) with base cases fib(0) = 0 and fib(1) = 1. It maps directly to the mathematical recurrence and is the standard teaching example for tree recursion.
The cost is the problem. Every call to fib(k) spawns two more calls, and those each spawn two more. The total number of function calls to compute fib(n) grows roughly as O(2^n). Computing fib(40) alone requires over a billion calls on a naive implementation.
Using this function to print the series up to n means calling it repeatedly in a loop, which compounds the cost further. The code below shows the pattern in all four languages for reference. Do not use it in production or under time constraints.
C
#include <stdio.h>
int fib(int k) {
if (k <= 1) return k;
return fib(k - 1) + fib(k - 2);
}
int main() {
int n, k = 0;
printf("Enter limit: ");
scanf("%d", &n);
while (fib(k) <= n) {
printf("%d ", fib(k));
k++;
}
printf("\n");
return 0;
}
C++
#include <iostream>
using namespace std;
int fib(int k) {
if (k <= 1) return k;
return fib(k - 1) + fib(k - 2);
}
int main() {
int n, k = 0;
cin >> n;
while (fib(k) <= n) {
cout << fib(k) << " ";
k++;
}
cout << endl;
return 0;
}
Java
import java.util.Scanner;
public class FibonacciRecursive {
static int fib(int k) {
if (k <= 1) return k;
return fib(k - 1) + fib(k - 2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = 0;
while (fib(k) <= n) {
System.out.print(fib(k) + " ");
k++;
}
System.out.println();
}
}
Python
def fib(k):
if k <= 1:
return k
return fib(k - 1) + fib(k - 2)
n = int(input("Enter limit: "))
k = 0
while fib(k) <= n:
print(fib(k), end=" ")
k += 1
print()
Note that the loop calls fib(k) twice per iteration: once in the condition and once in the print. A minor improvement is to store val = fib(k) before printing, but the fundamental O(2^n) cost per term remains.
Memoization: O(n) time, O(n) space
Memoization fixes the recursive approach by storing each computed Fibonacci term the first time it is calculated. On the next call with the same input, the function returns the cached value immediately. This brings the overall time complexity back down to O(n) while keeping the recursive call structure intact.
The trade-off is memory: the cache grows with n, so the space complexity is O(n). For most practical values of n, this is acceptable. When memory is a hard constraint, use the iterative approach instead.
C
#include <stdio.h>
#include <string.h>
#define MAX 100
long long memo[MAX];
long long fib_memo(int k) {
if (k <= 1) return k;
if (memo[k] != -1) return memo[k];
memo[k] = fib_memo(k - 1) + fib_memo(k - 2);
return memo[k];
}
int main() {
int n, k = 0;
memset(memo, -1, sizeof(memo));
scanf("%d", &n);
while (fib_memo(k) <= n) {
printf("%lld ", fib_memo(k));
k++;
}
printf("\n");
return 0;
}
C++
#include <iostream>
#include <unordered_map>
using namespace std;
unordered_map<int, long long> memo;
long long fib_memo(int k) {
if (k <= 1) return k;
if (memo.count(k)) return memo[k];
memo[k] = fib_memo(k - 1) + fib_memo(k - 2);
return memo[k];
}
int main() {
int n, k = 0;
cin >> n;
while (fib_memo(k) <= n) {
cout << fib_memo(k) << " ";
k++;
}
cout << endl;
return 0;
}
Java
import java.util.HashMap;
import java.util.Scanner;
public class FibonacciMemo {
static HashMap<Integer, Long> memo = new HashMap<>();
static long fib_memo(int k) {
if (k <= 1) return k;
if (memo.containsKey(k)) return memo.get(k);
long result = fib_memo(k - 1) + fib_memo(k - 2);
memo.put(k, result);
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = 0;
while (fib_memo(k) <= n) {
System.out.print(fib_memo(k) + " ");
k++;
}
System.out.println();
}
}
Python
memo = {}
def fib_memo(k):
if k == 0: return 0
if k == 1: return 1
if k in memo:
return memo[k]
memo[k] = fib_memo(k - 1) + fib_memo(k - 2)
return memo[k]
n = int(input("Enter limit: "))
k = 0
while fib_memo(k) <= n:
print(fib_memo(k), end=" ")
k += 1
print()
Comparing the three approaches
| Approach | Time complexity | Space complexity | When to use |
|---|---|---|---|
| Iterative | O(n) | O(1) | Interviews, production code, any constraint on memory |
| Recursive (plain) | O(2^n) | O(n) call stack | Teaching recursion concepts only |
| Memoization | O(n) | O(n) | When a recursive structure is required by the question |
If an interviewer asks “write Fibonacci up to n,” start with the iterative approach. If they then say “now do it recursively and optimise,” implement the plain recursive version first, walk through its cost, and add the memo table as the fix. Narrating that progression is worth more than jumping straight to memoization.
For placement-prep purposes, the iterative pattern also applies to related coding questions: check whether a number is in the Fibonacci series, find the index of a Fibonacci term, or generate the series into an array. Once the two-variable loop is solid, those variations are minor adjustments.
Fibonacci problems appear regularly in the data-structures and algorithms sections of placement tests at service-tier companies. The 20 most asked data structures interview questions with answers covers the broader category, including arrays and linked lists. For a companion multi-language coding exercise, see find the smallest and largest element in an array, and the iteration pattern there is directly comparable.
The memoization technique above is a direct application of dynamic programming: solve each sub-problem once and store the result. That same principle, caching expensive computations to avoid repeat work, appears in AI inference optimisation. If you want to see it in action in a real language-model context, TinkerLLM offers a ₹299 sandbox where you can run prompts and observe how the model handles repeated token patterns across calls.
Primary sources
Frequently asked questions
What is the difference between Fibonacci up to n and the n-th Fibonacci number?
Fibonacci up to n prints every term in the sequence whose value does not exceed n. The n-th Fibonacci number is a single value at position n. For limit n=20, the series is 0, 1, 1, 2, 3, 5, 8, 13. The 20th Fibonacci number (position-indexed from 0) is 6765.
Why is the recursive Fibonacci function so slow?
The naive recursive function recomputes the same sub-problems over and over. Calling fib(8) alone triggers 67 function calls because fib(n-1) and fib(n-2) each spawn their own complete trees. The total call count grows as O(2^n), making it unusable for n above roughly 35 to 40.
Which approach should I use in a coding interview?
Use the iterative two-variable approach for print-series-up-to-n questions. It is O(n) time, O(1) space, and immediately readable. If the interviewer asks you to start with recursion and then optimise, transition to memoization and explain the cache hit logic.
How do I print the Fibonacci series in Python efficiently?
Use tuple assignment in a while loop: set a, b = 0, 1 and loop while a <= n, printing a and then reassigning a, b = b, a + b. This is O(n) time, O(1) space, and the standard Python pattern for this problem.
What is the Fibonacci series for limit n=100?
For limit n=100, the series is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. The next term is 144, which exceeds 100, so the series stops at 89.
Does Fibonacci have a closed-form formula?
Yes — Binet's formula expresses the n-th Fibonacci number using powers of the golden ratio (approximately 1.618). In practice, floating-point rounding makes it unreliable for large n, so the iterative loop is always used in production code.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)