When I run my program it prints out the number for the forty eighth sequence as being -132375223 when it should read 4807526976. What am I doing wrong?
-Towey

# include <iostream>

using namespace std;
int main ()

{

    int x1=0;
    int x2=1;
    int fib;

    for (int i = 3; i <= 48; i++){
        fib = x1 + x2;
        x1 = x2;
        x2 = fib;
    }
    cout << fib << endl;

    return 0;
}

What am I doing wrong?

You're expecting int to have no limits. Let's assume the most likely scenario: you're using 32-bit integers. The largest signed value for int will be approximately 2147483647. The largest unsigned value doubles that to approximately 4294967295. In neither case can a 32-bit integer type hold your result of 4807526976, by a rather large margin too.

While overflow on a signed data type invokes undefined behavior, most of the time you'll see a modulo wraparound similar to how unsigned data types behave. This explains your negative result.

Thank you very much. ^_^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.