⚡ TL;DR
Display the Fibonacci series of the first n terms in C using a for loop. Complete source code with output, step-by-step explanation, and complexity analysis.
In this tutorial, you’ll learn how to display the Fibonacci sequence of the first n numbers (entered by the user) in the C programming language. The Fibonacci series starts with 0 and 1, and every subsequent term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, ...
Expected Output
For an input of 8 terms, the program should print:
Enter a positive number:
8
First 8 terms of Fibonacci series:
0
1
1
2
3
5
8
13Implementation
Fibonacci Series in C using a for loop:
#include<stdio.h>
int main()
{
int count, start = 0, second = 1, next, i;
//Ask user to input number of terms
printf("Enter a positive number:\n");
scanf("%d",&count);
printf("First %d terms of Fibonacci series:\n",count);
for ( i = 0 ; i < count ; i++ )
{
if ( i <= 1 )
next = i;
else
{
next = start + second;
start = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}Output
Enter a positive number:
8
First 8 terms of Fibonacci series:
0
1
1
2
3
5
8
13How It Works
The program keeps track of only the two most recent terms at any time:
- Seed values:
start = 0andsecond = 1are the first two Fibonacci numbers. - First two iterations: when
i <= 1, the term is simplyiitself (0, then 1) — no addition needed yet. - Every later iteration:
next = start + secondcomputes the new term, then the window slides forward —starttakes the oldsecond, andsecondtakes the freshly computednext. - Printing: each term is printed on its own line with
printf("%d\n", next).
Because the loop only ever stores three integers (start, second, next), the memory usage stays constant no matter how many terms you print.
Complexity
- Time: O(n) — one pass over the
nterms - Space: O(1) — only a fixed number of integer variables
Practice Variations
- Print the series up to a maximum value instead of a term count (e.g., all Fibonacci numbers below 100)
- Print the series on a single line separated by commas
- Compute the nth Fibonacci term using recursion instead of a loop
- Store the series in an array and print it in reverse
Happy coding!
