Fibonacci sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. This sequence is named after Leonardo Fibonacci, an Italian mathematician who introduced it to Western mathematics in his 1202 book Liber Abaci. The Fibonacci sequence is significant in various fields such as computer science, mathematics, and even nature. In this article, we will demonstrate how to generate the Fibonacci sequence using C++.

Code Example

#include <iostream>
#include <vector>

// Function to generate Fibonacci sequence
std::vector<int> generateFibonacciSequence(int numberOfTerms) {
    std::vector<int> sequence;
    if (numberOfTerms <= 0) return sequence;

    sequence.push_back(0);
    if (numberOfTerms == 1) return sequence;

    sequence.push_back(1);
    for (int i = 2; i < numberOfTerms; ++i) {
        int nextTerm = sequence[i-1] + sequence[i-2];
        sequence.push_back(nextTerm);
    }
    
    return sequence;
}

int main() {
    int numberOfTerms = 10;

    std::vector<int> sequence = generateFibonacciSequence(numberOfTerms);
    
    std::cout << "Fibonacci sequence: ";
    for (int term : sequence) {
        std::cout << term << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Code Explanation

Function to Generate Fibonacci Sequence

std::vector<int> generateFibonacciSequence(int numberOfTerms) {
    std::vector<int> sequence;
    if (numberOfTerms <= 0) return sequence;

    sequence.push_back(0);
    if (numberOfTerms == 1) return sequence;

    sequence.push_back(1);
    for (int i = 2; i < numberOfTerms; ++i) {
        int nextTerm = sequence[i-1] + sequence[i-2];
        sequence.push_back(nextTerm);
    }
    
    return sequence;
}

This function generates the Fibonacci sequence given the number of terms. It first checks if the number of terms is less than or equal to 0 and returns an empty sequence if true. For a sequence with only one term, it returns [0]. For more terms, it starts with [0, 1] and iteratively adds the sum of the two preceding terms to the sequence.

Main Function

int main() {
    int numberOfTerms = 10;

    std::vector<int> sequence = generateFibonacciSequence(numberOfTerms);
    
    std::cout << "Fibonacci sequence: ";
    for (int term : sequence) {
        std::cout << term << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

In the main function, we define the number of terms for the Fibonacci sequence. We then call the generateFibonacciSequence function with this parameter to generate the sequence. Finally, we print the sequence to the console.

Output

When the above code is executed, it produces the following output:

Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 

This output shows the first ten terms of the Fibonacci sequence starting with 0 and 1. Each term is generated by adding the two preceding terms, creating the classic Fibonacci sequence pattern.