Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

generate C++ program for fibonacci series

  1. User

    generate C++ program for fibonacci series

  2. Assistant

    Here is a C++ program to generate the Fibonacci series:

    #include <iostream>
    
    // Function to calculate Fibonacci series up to 'n' terms
    void fibonacciSeries(int n) {
        int first = 0, second = 1;
    
        // Print first two terms of the series
        std::cout << first << " " << second << " ";
    
        for (int i = 3; i <= n; i++) {
            int next = first + second;
            
            // Print the new term
            std::cout << next << " ";
    
            first = second;
            second = next;
        }
    }
    
    int main() {
        int n;
    
        std::cout << "Enter the number of terms in the Fibonacci series: ";
        std::cin >> n;
    
        std::cout << "Fibonacci Series up to " << n << " terms: ";
        fibonacciSeries(n);
    
        return 0;
    }
    

    In the above program, we first define a function fibonacciSeries() to calculate and print the Fibonacci series up to 'n' terms. We then prompt the user to enter the number of terms they would like to generate. Finally, we call the fibonacciSeries() function with the specified number of terms and print the resulting Fibonacci series.