C++ Online Compiler
Example: Recursive Fibonacci in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Recursive Fibonacci #include <iostream> // Function to calculate the nth Fibonacci number recursively int fibonacci(int n) { // Base cases: // The first Fibonacci number (at index 0) is 0. if (n == 0) { return 0; } // The second Fibonacci number (at index 1) is 1. else if (n == 1) { return 1; } // Recursive step: Sum of the two preceding numbers. else { return fibonacci(n - 1) + fibonacci(n - 2); } } int main() { // Step 1: Print the first 10 Fibonacci numbers std::cout << "Fibonacci Sequence (first 10 numbers):" << std::endl; for (int i = 0; i < 10; ++i) { std::cout << fibonacci(i) << " "; } std::cout << std::endl; // Step 2: Test with a specific number int num = 7; std::cout << "The " << num << "th Fibonacci number is: " << fibonacci(num) << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS