C Online Compiler
Example: Fibonacci Series - Recursive Method in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Fibonacci Series - Recursive Method #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 == 0) { return 0; } else if (n == 1) { return 1; } else { // Step 2: Recursive step - sum of the two preceding Fibonacci numbers. return (fibonacci(n - 1) + fibonacci(n - 2)); } } int main() { // Step 1: Declare variables for the number of terms and loop counter. int n, i; // Step 2: Prompt the user to enter the number of terms. printf("Enter the number of terms: "); scanf("%d", &n); // Step 3: Print a message indicating the series. printf("Fibonacci Series: "); // Step 4: Loop to call the recursive function for each term. for (i = 0; i < n; i++) { // Step 4.1: Call the fibonacci function and print the result. printf("%d, ", fibonacci(i)); } printf("\n"); // Newline for better formatting return 0; }
Output
Clear
ADVERTISEMENTS