📜  C++ fibo - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.108000             🧑  作者: Mango

C++ Fibo - C++

Introduction

In this article, we will explore the Fibonacci sequence and how it can be implemented using C++. We will provide a detailed explanation of the Fibonacci sequence, its properties, and then present a C++ code snippet that generates the Fibonacci series.

Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence starts with 0 and 1. The sequence can be defined by the following recurrence relation:

F(n) = F(n-1) + F(n-2), for n > 1

The Fibonacci sequence can be represented as: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

C++ Implementation

Here, we will provide a C++ code snippet to generate the Fibonacci series using recursive and iterative approaches.

Recursive Approach
#include <iostream>

int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    int numTerms = 10;
    std::cout << "Fibonacci Series using Recursive approach:" << std::endl;
    for (int i = 0; i < numTerms; ++i) {
        std::cout << fibonacci(i) << " ";
    }
    std::cout << std::endl;
    return 0;
}
Iterative Approach
#include <iostream>

void fibonacciIterative(int numTerms) {
    int term1 = 0, term2 = 1;

    std::cout << "Fibonacci Series using Iterative approach:" << std::endl;

    if (numTerms >= 1) {
        std::cout << term1 << " ";
    }
    if (numTerms >= 2) {
        std::cout << term2 << " ";
    }

    for (int i = 2; i < numTerms; ++i) {
        int nextTerm = term1 + term2;
        std::cout << nextTerm << " ";
        term1 = term2;
        term2 = nextTerm;
    }

    std::cout << std::endl;
}

int main() {
    int numTerms = 10;
    fibonacciIterative(numTerms);
    return 0;
}
Conclusion

In this article, we discussed the Fibonacci sequence, its properties, and how to implement it using C++. We provided code snippets for both the recursive and iterative approaches to generate the Fibonacci series. You can choose the approach according to your requirement and programming style.