C Program to Print Fibonacci Series - Iterative Approach
Print Fibonacci Series Iteratively
#include <stdio.h>
int main() {
int n;
// First two terms of the sequence
long long t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive integer.\n");
return 0;
}
printf("Fibonacci Series: ");
// Print the first term
if (n >= 1) {
printf("%lld ", t1);
}
// Print the second term
if (n >= 2) {
printf("%lld ", t2);
}
// Compute and print the rest of the terms
for (int i = 3; i <= n; ++i) {
nextTerm = t1 + t2;
printf("%lld ", nextTerm);
t1 = t2; // Move t2 to t1
t2 = nextTerm; // Update t2 to nextTerm
}
printf("\n");
return 0;
}
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
The Fibonacci sequence starts with 0 and 1, and each subsequent term is the sum of the previous two. By keeping track of the current and previous terms, you can generate the series iteratively without needing recursion. Using a long long type allows the program to handle larger numbers.
⬅ Previous TopicC Program - Find Factorial of a Number
Next Topic ⮕C Program - Find LCM of Two Numbers
Next Topic ⮕C Program - Find LCM of Two Numbers
Comments
Loading comments...