# Thread: do.. while loops

1. i figured out how to incorporate the switch statements into this program, but i am having trouble making the error term come up if the user tries to divide by zero.
Code:
```#include <iostream>
using namespace std;
int main()
{
double n=0, n2=0;
char operation;

cout << "Current Total is " << n << endl;

do
{
cout << "Enter an operation: + - * / (or enter X to exit):" << endl;
cin >> operation;
if (operation == 'X')
break;
cout << "Enter a number: " << endl;
cin >> n2;
switch (operation)
{
case '+':
n += n2;
break;
case '-':
n -= n2;
break;
case '*':
n *= n2;
break;
/*	case (('/') && (n2==0)):
cout << "Can not divide by zero!" << endl;
break;
*/
case '/':
n /= n2;
break;
}
cout << "Current Total is " << n << endl;
} while (operation != 'X');

}```
the part that is blocked off by the /* and */ is the part i dont know how to figure out. everything else works well with the program, but i dont know how to combine those two like an if statement would be able to do.

thanks for any help.

2. Like this:
Code:
```switch (operation)
{
case '+':
n += n2;
break;
case '-':
n -= n2;
break;
case '*':
n *= n2;
break;
case '/':
if (n2 == 0)
{
cout << "Can not divide by zero!" << endl;
}
else
{
n /= n2;
}
break;
}```
You could have done something like this for your if-else chain version too. It is good practice to check for equality of floating point numbers by checking a range.

3. thanks for the quick response. and for being very helpful.

4. Originally Posted by laserlight
You could have done something like this for your if-else chain version too. It is good practice to check for equality of floating point numbers by checking a range.
But in this case, the check should be exactly for zero, because you do not divide by zero unless you divide by zero If the value is non-zero the division should be allowed.

5. Originally Posted by brewbuck
But in this case, the check should be exactly for zero, because you do not divide by zero unless you divide by zero
I agree, but ask vart to explain otherwise:
Originally Posted by vart
also using == on doubles is not recomended...
Possibility of overflow in this case? I am not sure.

Popular pages Recent additions