[Solved] How can I avoid Arithmetic exception in this C++ code?


assuming int on your system is 32bit long, so the max number u can store in currentPrinter is 2,147,483,647 and minimum is -2,147,483,648. the reason you are getting arithmetic error is mainly caused because of dividing by zero but the reason you end up with divide by zero is because of the integer overflow.

if you cin the nocopy with 64, the for loop will run fine till i is 30.
at this point currentPrinter will be equal to 1,073,741,824 multiplying by that 2, will result in a value of 2,147,483,648 however, since this is an 32 bit int, the max number we can have is 2,147,483,647. and this is where the problem starts. because of the int overflow, instead of 2,147,483,647 currentPrinter would end up with -2,147,483,648. after the 31st iteration things get even worst.

during the 31st iteration, your currentPrinter again tries to multiply the -2,147,483,648 by 2 and this causes currentPrinter to become 0 which is again due to int overflow.

your 31st iteration is still fine. but on the 32nd iteration, the currentPrinter will cause a divide by zero error. hence the reason you get the divide by zero error.

enter image description here

solved How can I avoid Arithmetic exception in this C++ code?