What is meant by Fibonacci series/sequence? Write a program to generate Fibonacci sequence by using user defined functions.
The Fibonacci sequence or Fibonacci series, is defined as the sequence of numbers in which each number in the sequence is equal to the sum of two numbers before it. The Fibonacci Sequence is given as:
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21,..
Here, the third term 1 is obtained by adding first and second term. (which is: 0+1 = 1)
Similarly, 2 is obtained by adding the 2nd and 3rd term (1+1 = 2) while 3 is obtained by adding the 3rd and 4th term (1+2 = 3) and so on.
//C++ program to display Fibonacci sequence
#include<iostream>
using namespace std;
//Function definition
void fibonacciCalculator(int num);
int main()
{
int num;
cout<<"Enter the number of elements to print in the sequence: ";
cin>>num;
cout<<"Fibonacci sequence :";
cout<<"0 "<<"1 ";
fibonacciCalculator(num-2); //n-2 because 0 and 1 are already printed
return 0;
}
//Fibonacci function declaration -uses recursion
void fibonacciCalculator(int num)
{
static int n1=0, n2=1, n3;
if(num>0)
{
n3 = n1 + n2;
n1 = n2;
n2 = n3;
cout<<n3<<" ";
fibonacciCalculator(num-1);
}
}
Comments
Leave a comment