Fibonacci series program in C using recursion
In this program, you'll learn to display the Fibonacci sequence using a recursive function in C programming language.
The Fibonacci series are the sequence of numbers in which the next number is the sum of the previous two numbers. The Fibonacci series was well-known hundreds of years earlier. The "Fibonacci" name came from the nickname "Bonacci".
We can easily remember the Fibonacci Sequence using November 23rd as the Fibonacci Day. As November 23rd has the digits "1, 1, 2, 3", which is part of the sequence.
In the above image, the first two numbers are 0 and 1. So, according to the Fibonacci rule, the third number is 1 (sum of 0 and 1). The fourth number is 2, and so on.
0 + 1 = 1 // 0, 1, 1
1 + 1 = 2 // 0, 1, 1, 2
1 + 2 = 3 // 0, 1, 1, 2, 3
2 + 3 = 5 // 0, 1, 1, 2, 3, 5
0 ,1 , 1, 2, 3, 5, 8, 13, 21, 34....
Fibonacci Series Program in C using Recursive Function
A recursion function is a function that is called by itself. In the given example, we call the recursion function to get the Fibonacci series. A recursion function continues until some condition is met to prevent it. That's why we use the if statement to break the infinite recursion.
In the given program, we use recursion to generate the fibonacci series. The function fibonacciSeries() is called recursively until we get the result. In the function, we first check if the number n is greater than 0. If yes, we recursively call fibonacciSeries() with the values n-1 and n-2.
// C program to print Fibonacci series
#include<stdio.h>
// Recursive function
void fibonacciSeries(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
fibonacciSeries(n-1);
}
}
int main(){
int n;
printf("How many number of series? : ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
//Call Function
fibonacciSeries(n-2);
return 0;
}
Output 1
How many number of series? : 15
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Output 2
How many number of series? : 20
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative