C++ - Program - Fibonacci Series

#include <iostream>
// Function to generate Fibonacci series up to a given number of terms
void generateFibonacci(int n) {
    int first = 0;
    int second = 1;
    std::cout << "Fibonacci Series: ";
    // Display the first two terms
    std::cout << first << " " << second << " ";
    // Generate and display the remaining terms
    for (int i = 3; i <= n; i++) {
        int next = first + second;
        std::cout << next << " ";
        // Shift the values to generate the next term
        first = second;
        second = next;
    }
    std::cout << std::endl;
}
int main() {
    int numTerms;
    std::cout << "Enter the number of terms in the Fibonacci series: ";
    std::cin >> numTerms;
    // Generate and display the Fibonacci series
    generateFibonacci(numTerms);
    return 0;
}

In this program, we define a function generateFibonacci that takes the number of terms n as input and generates the Fibonacci series up to n terms. The function uses two variables first and second to keep track of the previous two terms of the series.

We start by displaying the first two terms (first and second) outside the loop. Then, using a for loop, we generate and display the remaining terms by adding the previous two terms. We update the values of first and second at each iteration to generate the next term.

In the main function, we prompt the user to enter the number of terms they want in the Fibonacci series. The input is stored in the variable numTerms. We then call the generateFibonacci function to generate and display the Fibonacci series with the specified number of terms.