Fibonacci series in C++

#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;
}

Try this instead. It's a bit of a different take but will get you there just the same.

#include <iostream>

using namespace std;

int main()
{
   int input(0), Alpha(0), Beta(1), Total(1);  
   cout << "Please input a top number: "; 
   cin >> input; 

   for(int i = 0; i <= input; i++)
   {
      cout << Total << endl; 
      Total = Alpha + Beta; 
      Alpha = Beta;
      Beta = Total; 
   }
} 

The Fibonacci Sequence is {0, 1, 1, 2, 3, ... N - 1, N, 2N - 1}.

In order to implement it, you need to have a N - 2 variable, and an N - 1 variable so that you can calculate N = (N - 2) + (N - 1):

unsigned int count = 0;
std::cin >> count;
// assume count >= 2
unsigned int prev2 = 0;
unsigned int prev1 = 1;

std::cout << prev2 << " " << prev1 << " ";
for (unsigned int i = 2; i < count; ++i)
{
    unsigned int current = prev2 + prev1;
    prev2 = prev1;
    std::cout << current << " ";
    prev1 = current; 
}
std::cout << std::endl;

Tags:

C++

Fibonacci