Reputation:
below is a do-while loop that I coded. When I run it, the first two cases do their job and run perfectly. However. the third case is supposed to quit the program but instead it does nothing and just goes back to the series of printf statements in the beginning of the do-while loop. Any suggestions as to what I am doing wrong?
do
{
printf("Choose one of the following (1, 2, or 3) \n");
printf("1. Find GCD of two positive integers\n");
printf("2. Sort 3 integers in the ascending order\n");
printf("3. Quit the program\n");
printf("Please enter your choice: ");
scanf("%d", &option);
switch (option)
{
case 1:
gcd(p, q);
printf("\nDo you want to try again? Say Y(es) or N(o): ");
getchar();
response = getchar();
break;
case 2:
sort(p, q, r);
printf("\nDo you want to try again? Say Y(es) or N(o): ");
getchar();
response = getchar();
break;
case 3:
break;
}
}
while (response == 'Y' || response == 'y'); //Condition that will determine whether or not the loop continues to run.
printf("\nThank you for using my progam. Goodbye!\n\n");
return 0;
}
Upvotes: 0
Views: 1016
Reputation: 224
You just interrupt the switch case.
How about using:
case 3:
return;
break;
Upvotes: 0
Reputation: 285
The break statement in case 3 just exits from case 3 rather than from the program. If you want to exit the program in case 3 then use the return statement.
return 0;
This statement exists the program rather than repeating the while loop.
Upvotes: 0
Reputation: 639
break
statement does not exit the program, it just exits from the switch
block.
To exit :
1.
#include<stdlib.h>
And instead of break
statement, use exit(0);
2.Change the case 3
as follows:
response='N';break;
Upvotes: 0
Reputation: 11
in case 3,there is no input coming from the user, so the response variable remains true, try asking the user for an input or just put response = '(any letter that will make the condition false)'
Upvotes: 0
Reputation: 9579
Do it like this:
case 3:
return 0;
You also might consider eliminating case 3 and just do this:
default:
return 0;
Upvotes: 1
Reputation: 3230
break
statement exits from first iterative loop. In your case this is switch
.
You must modify the response ( for example response =0).
case 3:
response=0; //different than 'Y' or 'y'
break;
Upvotes: 2
Reputation:
Response variable remains either Y or y and while loop never exits.
add
response = 'x'; //or something that isn't Y or y
before break; in case 3: option.
Upvotes: 2