C Online Compiler
Example: Fibonacci Series using Recursion in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series using Recursion #include <stdio.h> // Function to calculate the nth Fibonacci number recursively int fibonacci(int n) { // Step 1: Define the base cases // The first two Fibonacci numbers are 0 and 1 if (n <= 1) { return n; // fib(0) = 0, fib(1) = 1 } // Step 2: Define the recursive step // For n > 1, fib(n) is the sum of the two preceding numbers else { return fibonacci(n - 1) + fibonacci(n - 2); } } int main() { // Step 1: Declare the number of terms to print int terms = 10; int i; // Loop counter // Step 2: Print a header for the output printf("Fibonacci Series up to %d terms:\n", terms); // Step 3: Loop through each term from 0 to terms-1 // and call the fibonacci function to get its value for (i = 0; i < terms; i++) { printf("%d ", fibonacci(i)); } printf("\n"); // Print a newline character at the end return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS