Question

I need help with this code. Im using C++ coding. Non Recursive (iterative) Fibonacci Write a...

I need help with this code. Im using C++ coding.

Non Recursive (iterative) Fibonacci
Write a program that uses a for loop to calculate a Fibonacci sequence (NOT RECURSIVE!!!) up to a given position, starting with position 0. This function defines a Fibonacci sequence:

  • If the number is 0, the function returns a 0
  • If the number is 1, the function returns a 1
  • If the number is higher than 1, it returns the sum of the previous two numbers
The output should look something like this -- user inputs are in bold blue type:
How many elements do you want to display (starting with 0)? 18
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597
Thank you!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer: Hi!! Dear student, kindly find your solution below. Let me know if any issue. Thanks.

C++ code-

#include <iostream>
using namespace std;
int main() {
int num1=0,num2=1,num3,i,number;
cout<<"How many elements do you want to display? ";
cin>>number;
cout<<num1<<" "<<num2<<" "; //printing 0 and 1
for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed
{
num3=num1+num2;
cout<<num3<<" ";
num1=num2;
num2=num3;
}
return 0;
}

Output:

Add a comment
Know the answer?
Add Answer to:
I need help with this code. Im using C++ coding. Non Recursive (iterative) Fibonacci Write a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT