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; void printFibonacciIterative(int n) { // Step 1: Handle base cases for n=0 and n=1 if (n <= 0) { cout << "Please enter a positive integer." << endl; return; } if (n == 1) { cout << "0" << endl; return; } // Step 2: Initialize the first two Fibonacci numbers int a = 0; int b = 1; // Step 3: Print the first two numbers cout << a << " " << b << " "; // Step 4: Loop from the 3rd term up to n for (int i = 2; i < n; ++i) { int next = a + b; cout << next << " "; a = b; b = next; } cout << endl; } int main() { int count = 10; // Number of Fibonacci terms to generate cout << "Fibonacci Series (Iterative for " << count << " terms): "; printFibonacciIterative(count); return 0; }
Output
Clear
ADVERTISEMENTS