1. Home

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

• 130 Lessons
• 22 Hours
132

# Fibonacci Series in C

Updated on 12/09/2024211 Views

## 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

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.

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

Test your C programming skills with a Free Quiz

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

###### Need Guidance? We're Here to Help!
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. We’re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...