Fibonacci series using recursion in C++
In this post, you will learn how to write fibonacci series program using recursion in C++.
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 in C++ using recursion
A recursion function is a function that is called by itself. In the given C++ 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.
#include<iostream>
using namespace std;
void fibonacciSeries(int n){
static int n1=0, n2=1, n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
cout<<n3<<" ";
fibonacciSeries(n-1);
}
}
int main(){
int n;
cout<<"Enter the number of series: ";
cin>>n;
cout<<"Fibonacci Series: ";
cout<<"0 "<<"1 ";
fibonacciSeries(n-2);
return 0;
}
Output of the above code:
Enter the number of series: 11
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55
Related Articles
Bubble sort program in C++Priority queue in C++
GCD of two numbers in C++
Queue implementation in c++
Queue using linked list c++
Swapping of two numbers in C++
Generate random numbers in C++
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
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 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