Introduction

The Fibonacci series is a well-known sequence of numbers where each number is the sum of the two preceding numbers, starting from 0 and 1. The sequence is defined as follows:

  • F(0)=0F(0) = 0F(0)=0
  • F(1)=1F(1) = 1F(1)=1
  • F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2) for n>1n > 1n>1

Recursion is a programming technique where a function calls itself to solve smaller subproblems. This is particularly suitable for computing Fibonacci numbers due to its straightforward definition.

#include <stdio.h>

// Function to calculate Fibonacci number using recursion
int fibonacci(int n) {
    if (n == 0)
        return 0; // Base case 1
    else if (n == 1)
        return 1; // Base case 2
    else
        return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}

int main() {
    int terms, i;

    // Input: number of terms in the Fibonacci series
    printf("Enter the number of terms in the Fibonacci series: ");
    scanf("%d", &terms);

    printf("Fibonacci series: ");
    for (i = 0; i < terms; i++) {
        printf("%d ", fibonacci(i)); // Print each Fibonacci number
    }
    printf("\n");

    return 0;
}

Explanation

  1. Function Definition:
    • The fibonacci function takes an integer nnn as input.
    • It checks the base cases:
      • If n=0n = 0n=0, it returns 0.
      • If n=1n = 1n=1, it returns 1.
    • For n>1n > 1n>1, it calls itself recursively to compute the nnn-th Fibonacci number as the sum of the two preceding numbers.
  2. Main Function:
    • Prompts the user to enter the number of terms for the Fibonacci series.
    • Uses a loop to call the fibonacci function for each term and prints the result.

Input

When the program runs, it prompts for the number of terms in the Fibonacci series:

Enter the number of terms in the Fibonacci series: 10

Output

The program will output the Fibonacci series up to the specified number of terms:

Fibonacci series: 0 1 1 2 3 5 8 13 21 34

Conclusion

Using recursion to generate the Fibonacci series is a clear and illustrative example of how recursive functions work. While the recursive method is easy to implement and understand, it has limitations in terms of efficiency for large values of nnn due to its exponential time complexity. For practical applications, more efficient methods like iteration or memorization may be preferred. Nonetheless, this recursive approach effectively demonstrates fundamental concepts in programming and algorithm design.

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights