C++ Online Compiler
Example: Fibonacci Sequence Generator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Fibonacci Sequence Generator #include <iostream> int main() { int n; // Step 1: Prompt the user for the number of terms std::cout << "Enter the number of terms for the Fibonacci sequence: "; std::cin >> n; // Step 2: Handle edge cases for n if (n < 0) { std::cout << "Please enter a non-negative integer." << std::endl; return 1; // Indicate an error } else if (n == 0) { std::cout << "Fibonacci Sequence: (empty)" << std::endl; } else if (n == 1) { std::cout << "Fibonacci Sequence: 0" << std::endl; } else { // Step 3: Initialize the first two Fibonacci numbers int first = 0; int second = 1; std::cout << "Fibonacci Sequence: " << first << ", " << second; // Step 4: Use a loop to generate and print the remaining terms for (int i = 2; i < n; ++i) { int next = first + second; // Calculate the next number std::cout << ", " << next; // Print the next number first = second; // Update 'first' to the previous 'second' second = next; // Update 'second' to the newly calculated 'next' } std::cout << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS