When you enter the second number (y) as 0, this line:
printf("\nThe Quotant of %d and %d is: %d.",x,y,x/y);
attempts to divide by zero. This is bad and it makes your program abort execution.
I see that your code contains a logic check for y being set to zero; unfortunately, your code doesn't actually do anything about it. Looks like you have misunderstood how a do-while loop works. The condition is checked after each execution of the loop.
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117
how do you suggest i fix it? would a normal while loop work?
Yes. A normal while loop checks the condition before running the loop.
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117
tried ((x>0)&&(y!=0)) but that made no diffrence
It does make a difference. This code does not crash when the second value entered is zero. However, your code is a mess and once the while loop has been entered, the user is free to replace that value with zero pon a subsequent loop, and cause a crash.
#include <stdio.h>
int main () {
int x,y;
printf("\nPlease enter two real numbers: ");
scanf("%d%d", &x,&y);
if (x>0 && y==0) {
printf("\nError: Dividing by Zero");
printf("\nThe product of %d and %d is: %d.",x,y,x*y);
}
else if (x==0 && y==0) {
printf("\nEnd of Program");
}
while (x>0 && y!=0) {
printf("\nThe product of %d and %d is: %d.",x,y,x*y);
printf("\nThe Quotant of %d and %d is: %d.",x,y,x/y);
printf("\nPlease enter two real numbers: ");
scanf("%d%d", &x,&y);
if (x>0 && y==0) {
printf("\nError: Dividing by Zero");
printf("\nThe product of %d and %d is: %d.",x,y,x*y);
}
else if (x==0 && y==0) {
printf("\nEnd of Program");
}
};
return 0;
}
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117
Do you want the program to continue to run after the else if statement?
You do realize that if the value of y becomes 0 it will exit the loop right?
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
In that case how do you the loop to end?
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
This is a bit tidier and easier to understand. You'll need to work out how to end the loop.
#include <stdio.h>
int main () {
double x,y;
while (1) {
printf("\nPlease enter two real numbers (second cannot be zero): ");
scanf("%lf%lf", &x,&y);
printf("\nThe product of %3.2lf and %3.2lf is: %3.2lf.",x,y,x*y);
if (y!=0) {
printf("\nThe Quotant of %3.2lf and %3.2lf is: %3.2lf.",x,y,x/y);
}
else
{
printf("\nError: Dividing by Zero");
}
}
}
Moschops
Practically a Master Poster
620 posts since Sep 2008
Reputation Points: 258
Solved Threads: 117