#include <iostream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 1;
int num_temp;
int num_next = 1;
int n;
cin >> n;
for (int i = 0; i < n; i++){
cout << num_next << " ";
num_next = num1 + num2;
num1 = num2;
num_temp = num2;
num2 = num_next - num1;
num1 = num_temp;
}
return 0;
}
I have to output the first "n" fibonacci numbers however I think there is some problem in logic.. I can't find out what am I doing wrong. The first 3 or 4 elements are correct but then a problem occurs...
EXPECTED:
For n=9
0, 1, 1, 2, 3, 5, 8, 13, 21
Actual:
1 1 1 1 1 1 1 1 1
The Fibonacci formula is given as, Fn = Fn-1 + Fn-2, where n > 1.
Fibonacci Series Using Recursion in C refers to a number series. The Fibonacci series is created by adding the preceding two numbers ahead in the series. Zero and one are the first two numbers in a Fibonacci series. We generate the rest of the numbers by adding both the previous numbers in the series.
Fibonacci Sequence = 0, 1, 1, 2, 3, 5, 8, 13, 21, …. “3” is obtained by adding the third and fourth term (1+2) and so on. For example, the next term after 21 can be found by adding 13 and 21. Therefore, the next term in the sequence is 34.
#include <iostream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 1;
int num_temp;
int num_next = 1;
int n;
cin >> n;
if (n>=1)
cout << 0 << " ";
if (n>=2)
cout << 1 << " ";
for (int i = 0; i < n-2; i++){
num_next = num1 + num2;
cout << num_next << " ";
num1 = num2;
num2 = num_next;
}
cout << endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With