Print the First 10 Fibonacci Numbers

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.

Step-by-Step Objective

  • Initialize n1 = 0 and n2 = 1 as 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 shift n1 and n2.

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
Variable State Management Sequence Algorithms Iterative Patterns Algorithmic Foundations Value Swapping Logic Computational Thinking

Share this C++ Exercise

Help others learn algorithms and sequences in C++.

© C++ Programming Exercises. Master the art of performance coding.