C++ program to find fibonacci series upto N terms (without and with recursion)
In this chapter of C++ interview questions, we will learn to write:

c++ program to find fibonacci series

c++ program to find fibonacci series using recursion
Fibonacci series starts with like this
0,1,1,2,3,5,8,13,21,........
How fibonacci series works?

Next number we get by adding two numbers before it.

0 & 1 are the compulsory in the series.

0+1 = 1 → (0,1,1)

1+1 = 2 → (0,1,1,2)

1+2 = 3 → (0,1,1,2,3) and so on
So we can write equation for fibonacci series as
F_{n}=F_{n1}+F_{n2 } with F_{0}=0 and F_{1}=1(here n is a number choosed as input)
Now lets write a program to find fibonacci series in c++.
C++ program to find fibonacci series using recursion
For recursion there will be a base case which is n<=1, for any number inputed as n and returns n.
So the mathematical condition is
fibo(n) =n if n<=1
= fibo(n1)+fibo(n2) otherwise,
#include<iostream>
using namespace std;
int fibo(int n)
{
if(n<=1) // base case
return n;
return fibo(n1)+fibo(n2);
}
int main()
{
int n,i=0;
cin>>n;
while(i<n)
{
cout<<" "<<fibo(i);
i++;
}
return 0;
}
Output:
4
0 1 1 2
C++ program to find fibonacci series without recursion
Two predefined variable t1,t2 is there and assigned value 0 and 1 respectively.
A for loop will run for the inputed no.(n) of time. In the loop by adding two numbers before, the new number is printed, the series continues.
#include <iostream>
using namespace std;
int main() {
int i, n, t1 = 0, t2 = 1, nT;
cin>>n;
for (i = 1; i <= n; ++i) {
cout<<t1<<" ";
nT = t1 + t2;
t1 = t2;
t2 = nT;
}
return 0;
}
Output:
5
0 1 1 2 3
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 17,2021