The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1. The series goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

Fibonacci Series Formula

The Fibonacci sequence can be defined recursively as follows:

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

Implementation in C

You can implement the Fibonacci series in C using either recursion or iteration. Below are examples for both methods.

Example 1: Fibonacci Series Using Iteration

#include <stdio.h> void fibonacciIterative(int n) { int first = 0, second = 1, next; printf("Fibonacci Series (Iterative):\n"); printf("%d, %d", first, second); // Print the first two numbers for (int i = 2; i < n; i++) { next = first + second; // Calculate the next number printf(", %d", next); // Print the next number first = second; // Update first to the previous second second = next; // Update second to the newly calculated number } printf("\n"); } int main() { int n; printf("Enter the number of terms in Fibonacci Series: "); scanf("%d", &n); fibonacciIterative(n); // Call the function return 0; }

Explanation:

  • The fibonacciIterative function computes the Fibonacci series iteratively.
  • It starts by initializing the first two numbers (0 and 1) and then calculates the next numbers in the series using a loop.
  • The loop continues until the desired number of terms is reached.

Example 2: Fibonacci Series Using Recursion

#include <stdio.h> // Recursive function to calculate Fibonacci number int fibonacciRecursive(int n) { if (n == 0) return 0; // Base case if (n == 1) return 1; // Base case return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); // Recursive call } void printFibonacciRecursive(int n) { printf("Fibonacci Series (Recursive):\n"); for (int i = 0; i < n; i++) { printf("%d, ", fibonacciRecursive(i)); // Print Fibonacci number at position i } printf("\n"); } int main() { int n; printf("Enter the number of terms in Fibonacci Series: "); scanf("%d", &n); printFibonacciRecursive(n); // Call the function return 0; }

Explanation:

  • The fibonacciRecursive function calculates the Fibonacci number for a given position using recursion.
  • The printFibonacciRecursive function prints the Fibonacci series by calling the recursive function for each term.
  • The base cases handle the first two numbers of the Fibonacci sequence.

Output Example

For both implementations, if you enter 10 when prompted, the output will be:

Fibonacci Series (Iterative): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Fibonacci Series (Recursive): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Summary

  • The Fibonacci series is a classic example of a sequence defined recursively.
  • It can be implemented in C using either iterative or recursive methods.
  • The iterative approach is generally more efficient than the recursive one, especially for larger terms, as it avoids the overhead of multiple function calls and reduces redundant calculations.