top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Fibonacci Series in C

Introduction

Understanding the Fibonacci series and its implementation, particularly Fibonacci series in C using recursion, is a vital skill for any programmer. This tutorial delves into the intricacies of recursion in C to compute the Fibonacci series, illuminating how simple yet powerful this concept can be.

Overview

The Fibonacci series is a cornerstone concept in both mathematics and computer science, occurring in various algorithms and mathematical theorems. This tutorial will focus on implementing the Fibonacci series, especially in the C programming language, using the method of recursion.

What is a Fibonacci Series?

A Fibonacci series can be defined as a sequence of numbers where each number in the series will always be the sum of the two preceding numbers, usually starting with 0 and 1. The occurrence of this sequence in computing algorithms, mathematical theorems, and nature makes it an important skill for programmers. 

Fibonacci Series in C Using Recursion

Code:

// Fibonacci Series using Recursion
#include<stdio.h>
#include<conio.h>
// Fibonacci Series using Recursion
#include <stdio.h>
int fibonacci(int x)
{
if (x <= 1)
return x;
return fibonacci(x - 1) + fibonacci(x - 2);
}

int main()
{
int a = 3;
printf("%dth Fibonacci Number: %d", a, fibonacci(a));
return 0;
}

Explanation:

fibonacci function: This function takes an integer x as input and calculates the Fibonacci number for that input using recursion. This example of Fibonacci series using recursion follows the standard Fibonacci sequence definition: F(n) = F(n-1) + F(n-2). The base case for the recursion is when x is 0 or 1, in which case it directly returns x.

main function: In the main function, the variable a is initialized with the value 3 which represents the desired position of the Fibonacci number in the sequence that we want to find.

printf: The printf statement in the main function prints the result. It uses the Fibonacci function to calculate the 3rd Fibonacci number (a), and then it displays the result with the format string: "%dth Fibonacci Number: %d".

Explanation of the output:

The Fibonacci sequence starts with 0, 1, and then each subsequent number is the sum of the two preceding ones. So, the 3rd Fibonacci number is the sum of the 1st and 2nd Fibonacci numbers, which are 0 and 1 respectively. Therefore, the 3rd Fibonacci number is 1 + 1 = 2.

Fibonacci Series in C Without Recursion

Code:

#include<stdio.h>    
int main()    
{    
 int x1=0,x2=1,x3,a,num;    
 printf("Enter the number of elements:");    
 scanf("%d",&num);    
 printf("\n%d %d",x1,x2);//printing 0 and 1    
 for(a=2;a<num;++a)//loop starts from 2 because 0 and 1 are already printed    
 {    
  x3=x1+x2;    
  printf(" %d",x3);    
  x1=x2;    
  x2=x3;    
 }  
  return 0;  
 }    

Explanation:

Variables: The variables x1, x2, and x3 are used to hold the Fibonacci sequence elements, and the variable num is used to store the number of elements in the Fibonacci series that the user wants to generate.

Input: The program prompts the user to enter the number of elements they want in the Fibonacci series using the printf and scanf functions.

Loop: The program uses a for loop to generate and print the Fibonacci series. The loop starts from a = 2 because the first two Fibonacci numbers 0 and 1 are already known and printed outside the loop.

Fibonacci Calculation: Within the loop, the next Fibonacci number x3 is calculated as the sum of the two previous Fibonacci numbers (x1 and x2), following the sequence: F(n) = F(n-1) + F(n-2).

Printing: The printf statement inside the loop prints the value of x3, which is the next Fibonacci number in the series.

Shifting: After printing the x3 value, the variables x1 and x2 are shifted to hold the values of the two previous Fibonacci numbers for the next iteration.

Return: The program returns 0, indicating successful completion of the main function.

When you run this code and input a number, it will generate and print the Fibonacci series with the specified number of elements. For example, if you input 10, the program will output the first 10 Fibonacci numbers.

Calculating Fibonacci and its Mathematical Representation

Mathematical Representation of the Fibonacci Sequence:

The nth Fibonacci number, denoted as F(n), can be mathematically represented as:

F(0) = 0

F(1) = 1

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

In this representation:

F(0) and F(1) are the base cases of the sequence, and they are explicitly defined as 0 and 1, respectively.

For n >= 2, each Fibonacci number is calculated as the sum of the two preceding Fibonacci numbers, F(n-1) and F(n-2).

Using this mathematical representation, we can find any desired Fibonacci number by recursively applying the formula or by using iterative methods, as shown in the previous code examples.

For example:

F(2) = F(1) + F(0) = 1 + 0 = 1

F(3) = F(2) + F(1) = 1 + 1 = 2

F(4) = F(3) + F(2) = 2 + 1 = 3

F(5) = F(4) + F(3) = 3 + 2 = 5

And so on, following the Fibonacci sequence.

It's worth noting that the Fibonacci sequence has many interesting properties and appears in various natural phenomena and mathematical contexts. Its recursive nature is often used as a simple example to illustrate recursion in programming.

Here is an example:

Code:

#include <stdio.h>
int main() {

  int i, n;

  // initialize first and second terms
  int x1 = 0, x2 = 1;

  // initialize the next term (3rd term)
  int nextTerm = x1 + x2;

  // get no. of terms from user
  printf("Enter the number of terms: ");
  scanf("%d", &n);

  // print the first two terms t1 and t2
  printf("Fibonacci Series: %d, %d, ", x1, x2);

  // print 3rd to nth terms
  for (i = 3; i <= n; ++i) {
    printf("%d, ", nextTerm);
    x1 = x2;
    x2 = nextTerm;
    nextTerm = x1 + x2;
  }

  return 0;
}

Explanation:

Variables: The code declares variables i (used as a loop counter) and n to store the number of terms in the Fibonacci series that the user wants to generate.

Initialization: The variables x1 and x2 are initialized to 0 and 1, respectively. These represent the first two terms of the Fibonacci series.

Calculation: The variable nextTerm is initialized as the sum of x1 and x2, representing the third term in the Fibonacci series.

Printing: The program prints the first two terms (x1 and x2) of the Fibonacci series using printf. The loop will generate and print the remaining terms.

Loop: The for loop runs from i = 3 to n. This loop generates the remaining Fibonacci terms (from the 3rd to the nth term).

Fibonacci Calculation: Within the loop, the variable nextTerm is calculated as the sum of the previous two terms (x1 and x2), following the sequence: F(n) = F(n-1) + F(n-2).

Shifting: After calculating nextTerm, the variables x1 and x2 are updated with the values of the previous two terms for the next iteration.

Printing the remaining terms: The printf statement inside the loop prints the value of nextTerm, which is the next Fibonacci number in the series.

Another Example of a Program Calculating Fibonacci Series Numbers

Code:

#include<stdio.h>    
void printFibonacci(int p){    
    static int x1=0,x2=1,x3;    
    if(p>0){    
         x3 = x1 + x2;    
         x1 = x2;    
         x2 = x3;    
         printf("%d ",x3);    
         printFibonacci(p-1);    
    }    
}    
int main(){    
    int a;    
    printf("Enter the number of elements: ");    
    scanf("%d",&a);    
    printf("Fibonacci Series: ");    
    printf("%d %d ",0,1);    
    printFibonacci(a-2);//a-2 because 2 numbers are already printed    
  return 0;  
 }    

Explanation:

printFibonacci function: This function is a recursive function that prints the Fibonacci series. It uses static variables x1, x2, and x3 to keep track of the last three Fibonacci numbers. The function takes an integer p as input, representing the number of elements remaining to be printed in the series.

Base Case: The function checks if p is greater than 0, which serves as the base case for the recursion. If p is 0 or negative, the function returns without doing anything, terminating the recursion.

Fibonacci Calculation: Within the function, the next Fibonacci number x3 is calculated as the sum of x1 and x2, following the sequence: F(n) = F(n-1) + F(n-2).

Shifting: After calculating x3, the variables x1 and x2 are updated to x2 and x3, respectively, to prepare for the next iteration.

Printing: The printf function prints the value of x3, which is the next Fibonacci number in the series.

Recursive Call: The function calls itself (printFibonacci) with p-1 as the new argument. This leads to the printing of the next Fibonacci number in the series, and the recursion continues until the base case is reached.

main function: In the main function, the variable a is used to store the number of elements the user wants in the Fibonacci series.

Printing Initial Values: The program prints the first two Fibonacci numbers (0 and 1) as the initial elements of the series.

printFibonacci: The printFibonacci function is called with a-2 as the argument since the first two numbers (0 and 1) are already printed. This function generates and prints the remaining Fibonacci numbers.

Conclusion

Mastering recursion and its application in problems like the Fibonacci series is a significant milestone for any C programmer. Although the Fibonacci series in C using recursion is a simple concept, it lays the foundation for understanding complex recursive problems.

For those of you who are interested in delving deeper into C programming and other advanced topics, upGrad offers comprehensive online programs tailored to your needs. Happy coding!

FAQs

  1. What is the benefit of using recursion for the Fibonacci series in C?

Recursion provides an intuitive and straightforward solution to the Fibonacci series. However, care must be taken to manage resources efficiently.

  1. How does the recursive solution for the Fibonacci series in C differ from Python?

The fundamental concept remains the same, but Python handles recursion slightly differently due to its inherent language features.

  1. Are there any potential pitfalls while using recursion in C?

Yes, excessive recursion without proper termination conditions can lead to a stack overflow. Always ensure your recursive function has a terminating condition.

  1. Why is the Fibonacci series significant in computer science?

The Fibonacci series is widely used in algorithms and data structures, such as dynamic programming, and is also a popular problem to test a candidate's understanding of recursion and iteration.

  1. Where can I learn more about advanced programming concepts in C?

upGrad offers comprehensive online programs covering advanced C programming concepts, designed specifically for working professionals looking to upskill.

Leave a Reply

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