Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci series in C++

Tags:

c++

fibonacci

#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

like image 430
user2943407 Avatar asked Oct 31 '13 23:10

user2943407


People also ask

What is Fibonacci Series formula?

The Fibonacci formula is given as, Fn = Fn-1 + Fn-2, where n > 1.

What is Fibonacci series in C using recursion?

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.

What is Fibonacci series example?

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.


1 Answers

#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;
}
like image 128
hasan Avatar answered Sep 28 '22 18:09

hasan