0

I need to find out how to control the flow of the program so that the program does not crash when the user inserts huge numbers. The goal of the program is to calculate the Fibonacci series, by the user's input.

#include <iostream>
using namespace std;

int main() {

int n;   
cout << " Please enter number of fibonacci number series you wanna see  ";   
cin >> n;     
int num1=0;
int num2=1;
cout << num1 << " " << num2 << " ";

if(num1+num2<=32756)

for (int i=0; i<=n-1; ++i)
{
    int num2Temp=num2;
    cout << num1+num2 << " ";
    num2=num1+num2;
    num1=num2Temp;

}
else 
    cout << " TOO BIG " << endl;

return 0;
}

I do calculate the Fibonacci series, however, it does not follow the if statement and stops the program as it exceeds the 32756. I understand why it does it as the num1+num2 is not updated, so that program understand it 0+1, no the update versions for each loop. But I do not have a specific idea to fix the program.

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35

1 Answers1

0

You only test the sum once, before your loop starts.

You probably want to test inside the loop, and exit it if the sum exceeds 32756:

for (int i = 0; i < n; i++)
{
    if (num1 + num2 <= 32756)
    {
        int num2Temp = num2;
        num2 += num1;
        num1 = num2Temp;
        cout << num2 << " ";
    }
    else
    { 
        cout << " TOO BIG " << endl;
        break;
    }
}
Sid S
  • 6,037
  • 2
  • 18
  • 24