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 base cases for the recursion // The 0th Fibonacci number is 0 if (n == 0) { return 0; } // The 1st Fibonacci number is 1 else if (n == 1) { return 1; } // Step 2: Recursive step for n > 1 // The nth Fibonacci number is the sum of the (n-1)th and (n-2)th numbers else { return fibonacci(n - 1) + fibonacci(n - 2); } } int main() { int terms, i; // Step 3: Prompt user for the number of terms printf("Enter the number of terms for the Fibonacci series: "); scanf("%d", &terms); // Step 4: Validate input if (terms < 0) { printf("Please enter a non-negative number of terms.\n"); return 1; // Indicate an error } // Step 5: Print the series printf("Fibonacci Series: "); for (i = 0; i < terms; i++) { printf("%d ", fibonacci(i)); // Call the recursive function for each term } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS