🔢 Fibonacci Series Using Loop in C++
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. It is widely used in mathematics, computer science, and even in nature.
📘 What Is the Fibonacci Series?
A Fibonacci sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Each term is generated by adding the two previous terms. The first two numbers are typically 0 and 1.
🔧 C++ Code to Generate Fibonacci Series Using Loop
#include <iostream>
using namespace std;
int main() {
int n, first = 0, second = 1, next;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i) {
cout << first << " ";
next = first + second;
first = second;
second = next;
}
return 0;
}
✅ Sample Output
Enter the number of terms: 7 Fibonacci Series: 0 1 1 2 3 5 8
📝 How It Works
- We initialize the first two terms as
0
and1
. - Using a
for
loop, we calculate each next term by adding the previous two. - We then shift the values forward: the second number becomes the new first, and the newly calculated number becomes the new second.
- This continues until we reach the desired number of terms.
📗 Definition: Fibonacci Series Using Loop
The Fibonacci series using a loop in C++ is a method of generating the Fibonacci sequence by repeatedly updating the last two terms in a loop. Unlike recursion, this method is more efficient in terms of memory and performance, making it ideal for large sequences.
🎯 Conclusion
The Fibonacci series is a foundational concept in programming and mathematics. By using loops, we can efficiently generate any number of terms with minimal resource usage. This technique is useful in many real-world applications including cryptography, search algorithms, and dynamic programming.
Post a Comment