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?

# 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;
6 Years
Discussion Span
Last Post by ToweyLeake

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.

Edited by Narue: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.