C++ Online Compiler
Example: Fibonacci Sequence up to Nth Term in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Fibonacci Sequence up to Nth Term #include <iostream> using namespace std; int main() { // Step 1: Declare variables int n; // Stores the desired number of terms int firstTerm = 0; // Initialize the first Fibonacci term int secondTerm = 1; // Initialize the second Fibonacci term int nextTerm; // To store the sum of the previous two terms // Step 2: Prompt user for input cout << "Enter the number of terms (n) for Fibonacci sequence: "; cin >> n; // Step 3: Handle edge cases for n if (n < 0) { cout << "Please enter a non-negative integer." << endl; } else if (n == 0) { cout << "Fibonacci sequence up to 0 terms: " << endl; } else if (n == 1) { cout << "Fibonacci sequence up to 1 term: " << endl; cout << firstTerm << " "; } else { // Step 4: Print the first two terms cout << "Fibonacci sequence up to " << n << " terms: " << endl; cout << firstTerm << " " << secondTerm << " "; // Step 5: Loop to calculate and print subsequent terms for (int i = 3; i <= n; ++i) { // Loop starts from the 3rd term nextTerm = firstTerm + secondTerm; // Calculate the next term cout << nextTerm << " "; // Print the next term firstTerm = secondTerm; // Update firstTerm to the previous secondTerm secondTerm = nextTerm; // Update secondTerm to the newly calculated nextTerm } cout << endl; // New line after printing the sequence } return 0; }
Output
Clear
ADVERTISEMENTS