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