Print the First 10 Fibonacci Numbers in C++
Master iterative logic and variable updates by generating the famous Fibonacci sequence, where each number is the sum of the two preceding ones.
Logic and Sequence
Value Swapping
To move forward in the sequence, we must "shift" our variables: the current value becomes the new previous, and the sum becomes the new current.
Iterative Generation
Using a for loop, we automate the addition of n1 + n2 exactly 10 times to produce the required output.
Key Concepts Learned:
- Sequence Logic: Understanding the formula $F_n = F_{n-1} + F_{n-2}$.
- State Management: Updating multiple variables within a loop.
- Algorithmic Thinking: Building the foundation for recursion and patterns.
Course:
Introduction to C++
Step-by-Step Objective
- Initialize
n1 = 0andn2 = 1as the starting points. - Set up a loop that iterates 10 times.
- Print the current number (
n1) in each iteration. - Update variables: calculate
next = n1 + n2, then shiftn1andn2.
C++ Solution
fibonacci_sequence.cpp
C++ Beginners
#include <iostream>
using namespace std;
int main() {
int n1 = 0, n2 = 1, next;
cout << "The first 10 Fibonacci numbers are: " << endl;
for (int i = 1; i <= 10; ++i) {
cout << n1 << " "; // Print the current number
// Logic to update the sequence
next = n1 + n2;
n1 = n2;
n2 = next;
}
cout << endl;
return 0;
}
Console Output:
The first 10 Fibonacci numbers are:
0 1 1 2 3 5 8 13 21 34
Iterative Logic & State Shifting