In: Computer Science
Write the code (in a function) that allows the user to display the first “nb” of elements in the Fibonacci sequence (each value on a separate line in the console).
The order of the Fibonacci sequence goes as follows: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 and on to infinity. Each number is the sum of the previous two (with the 2 starting numbers being 1 and 1). This series of numbers is known as the Fibonacci numbers or the Fibonacci sequence.
The function name should be “fibonacci” and it should take an integer as a parameter (argument), i.e. “fibonacci(int nb)”.
When called the function should respond as follows:
Function call:
fibonacci(1);
Console result:
1
Function call:
fibonacci(2);
Console result:
1
1
Function call:
fibonacci(3);
Console result:
1
1
2
And so on, …
ANS:
#include<string>
#include<iostream>
using namespace std;
void fibonacci(int nb)
{
cout<<"PROGRAM OF FIBONACCI"<<endl;
int x=1;
int x2=1;
int next=0;
for(int i=1;i<=nb;i++)
{
if(i==1)
{
cout<<x<<endl;
continue;
}
if(i==2)
{
cout<<x2<<endl;
continue;
}
next=x+x2;
x=x2;
x2=next;
cout<<next<<endl;
}
}
int main()
{
cout<<"NB=3"<<endl;
fibonacci(3);
cout<<endl<<endl<<"NB=2"<<endl;
fibonacci(2);
}
Comment down for any queries
Please give a thumbs up if you are satisfied with answer
:)