Fibonacci sequence Write a program that computes the Fibonacci number for some i
ID: 3758833 • Letter: F
Question
Fibonacci sequence
Write a program that computes the Fibonacci number for some input integer. The sequence is defined as the first two elements are each 1, after that each element in the sequence is the sum of the previous two elements. The first few numbers of the sequence are 1,1,2,3,5,8,13,21,34,55,…
Your assignment is to write a program with a main method and two additional methods. The main method will request theindex into the Fibonacci sequence that is desired and verify that it is a positive integer. If it is not a positive integer, it will request that the use input a number again. Note that I will test this using letters, decimal numbers, negative integers, etc. and it must handle these problems without erroring off. It will do so until the use inputs a positive integer. It will then invoke the two methods each of which will compute the required Fibonacci number. One method will use recursion to do so and another will use iteration. Your main method will output the determined Fibonacci number from each of the methods (they had better be the same).
Send me an e-mail with your source code attached along with a sample output from your program. Also make detailed comments on the efficiency of the two methods.
Explanation / Answer
#include <iostream>
using namespace std;
int fib_iter(int);
int fibonacci_rec(int);
int main(int argc, char** argv) {
int n; // Please note i have taken input in Integer type So if user input decimal value It will automatically convert in to integer.
cout<<"Enter N you want to calculate"<<endl;
cin>>n;
while(n<=0)
{
cout<<"Please input correct integer which should be grater than 0"<<endl;
cin>>n;
}
if(n==1||n==2)
cout<<1<<endl;
if(n>2)
{
cout<<"Using reccursive "<<fibonacci_rec(n)<<endl;
cout<<"Using Iterative "<<fib_iter(n)<<endl;
}
return 0;
}
int fibonacci_rec(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci_rec(n-1) + fibonacci_rec(n-2);
}
}
int fib_iter(int n)
{
int previous = 1;
int current = 1;
int next = 1;
for (int i = 3; i <= n; ++i)
{
next = current + previous;
previous = current;
current = next;
}
return next;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.