C Fibonacci Series Using Recursion Program
The "Fibonacci Series Using Recursion" program in C generates the Fibonacci series up to a specified number of terms using a recursive function. The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1. The series looks like this:
Fibonacci Sequence Definition
The Fibonacci sequence can be defined recursively as follows:
- for
Implementation of Fibonacci Series Using Recursion
Here’s a simple implementation of the Fibonacci series program using recursion in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header is included for standard input and output functions.
Function Declaration:
int fibonacci(int n)
: This function takes an integern
and returns the Fibonacci number.
Base Cases:
- The base cases check if
n
is 0 or 1. Ifn
is 0, it returns 0, and ifn
is 1, it returns 1.
- The base cases check if
Recursive Case:
- If
n
is greater than 1, the function calls itself twice: once withn - 1
and once withn - 2
, and returns the sum of these two calls. This builds the Fibonacci sequence by calculating previous terms recursively.
- If
Main Function:
- The program starts by prompting the user to enter the number of terms for the Fibonacci series.
- It uses
scanf()
to read the input value.
Generating the Series:
- A loop runs from 0 to the specified number of terms. For each iteration, it calls the
fibonacci()
function and prints the result.
- A loop runs from 0 to the specified number of terms. For each iteration, it calls the
Output:
- The program prints the Fibonacci series up to the specified number of terms.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter the number of terms when prompted.
Example Input/Output
Input:
Output:
Conclusion
The "Fibonacci Series Using Recursion" program in C demonstrates how recursion can be applied to generate sequences. While this implementation is straightforward and easy to understand, it is important to note that this recursive approach has exponential time complexity due to overlapping subproblems. For larger values of n
, an iterative or memoized approach would be more efficient. Nonetheless, this program serves as a good introduction to recursion in C programming.