C++ How To Print the Fibonacci Sequence
Print the Fibonacci Sequence
In the Fibonacci sequence, each number is the sum of the two numbers before it: 0, 1, 1, 2, 3, 5, 8, and so on:
Example
int n = 10;
int a = 0;
int b = 1;
for (int i = 0; i < n; i++) {
cout << a << " ";
int next = a + b;
a = b;
b = next;
}
Explanation:a and b hold the last two numbers.
Each time the loop runs, we print a, calculate the next number, and move both variables one step forward.