C++ Online Compiler
Example: Fibonacci Series - Iterative in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Fibonacci Series - Iterative #include <iostream> using namespace std; int main() { int n; cout << "Enter the number of terms: "; cin >> n; int t1 = 0, t2 = 1; // Initialize the first two terms int nextTerm = 0; cout << "Fibonacci Series: "; // Step 1: Handle cases for n = 1 or n = 2 if (n == 0) { cout << "No terms to display." << endl; return 0; } else if (n == 1) { cout << t1 << endl; return 0; } else { // Step 2: Print the first two terms cout << t1 << ", " << t2; } // Step 3: Calculate and print subsequent terms for (int i = 3; i <= n; ++i) { nextTerm = t1 + t2; cout << ", " << nextTerm; t1 = t2; // Update t1 to the previous t2 t2 = nextTerm; // Update t2 to the newly calculated nextTerm } cout << endl; return 0; }
Output
Clear
ADVERTISEMENTS