Switch statement closing [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am writing a switch statement that is supposed to act like a simple calculator, and when I select case 5 it's supposed to toggle between single and double precision. However when I select case 5, I get Calculator now works with double precision. and it exits the program. It was actually working before until I added case 6 which is supposed to be the one that exit's the program.
int opt;
float first, second, sum, difference, product, quotient;
double first_d, second_d, sum_d, difference_d, product_d, quotient_d;
char ch;
printf("This program implements a calculator. Options:\n");
printf(" 1 - addition\n 2 - subtraction\n 3 - multiplication\n 4 - division\n");
printf(" 5 - toggle precision\n 6 - exit program");
ch = getchar();
for(;;) {
printf("Please enter your option:");
scanf("%d", &opt);
switch (opt) {
case 1:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
sum = first + second;
printf("The sum is: %f\n", sum);
break;
case 2:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
difference = first - second;
printf("the difference is: %f\n", difference);
break;
case 3:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
product = first * second;
printf("The product is: %f\n", product);
break;
case 4:
printf("Enter first term:");
scanf("%f", &first);
printf("Enter second term:");
scanf("%f", &second);
quotient = first/ (float)second;
printf("The quotient is: %f\n", quotient);
if(second == 0){
printf("Cannot divide by 0!\n");
}
break;
case 5:
if(ch != '1' && '2' && '3' && '4' && '6'){
printf("Calculator now works with double precision.\n");
switch (opt) {
case 1:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
sum_d = first_d + second_d;
printf("The sum is: %lf\n", sum_d);
break;
case 2:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
difference_d = first_d - second_d;
printf("the difference is: %lf\n", difference_d);
break;
case 3:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
product_d = first_d * second_d;
printf("The product is: %lf\n", product_d);
break;
case 4:
printf("Enter first term:");
scanf("%lf", &first_d);
printf("Enter second term:");
scanf("%lf", &second_d);
quotient_d = first_d/ (double)second_d;
printf("The quotient is: %lf\n", quotient_d);
if(second_d == 0){
printf("Cannot divide by 0!\n");
} else {
printf("Calculator now works with single precision.\n");
}
break;
}
}
case 6:
return 0;
default:
printf(" 1 - addition\n 2 - subtraction\n 3 - multiplication\n 4 - division\n");
printf(" 5 - toggle precision\n 6 - exit program\n");
break;
}
}
}

As the comments on your original post have said, you simply forgot a break.
After your fifth case, a break would cause the code to leave the switch statement and continue looping input. Because you forgot this break, the code finished in the fifth case and continued into the sixth case. The sixth case then exits, which is what your output was originally.
Add a break statement at the end of the fifth case, and you should be all set to go.

Related

Do while loop in a switch statement

Using just the switch statement works totally fine. My problem comes when inserting the do-while loop. On the first try, the program works smoothly, but in the second and following loops, after asking the user if he wants to try again by typing 1, the program "jumps" the part where the user writes its input (scanf("%d", &oper)) and executes the rest of the program considering the previously typed 1 as the input and messing up everything.
I´ve tried looking for the answer on similar questions and videos, but I´m quite new and I just can´t grasp it. I have another program with a similar problem. I will really appreciate your help :)
#include <stdio.h>
int main()
{
int num1, num2, oper, select;
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter the number 1-5 to for the operations\n");
printf("1-Addition\n");
printf("2-Subtraction\n");
printf("3-Division\n");
printf("4-Multiplication\n");
printf("5-Modulo\n");
scanf("%d", &oper);
do{
printf("Press 0 to stop and 1 to continue");
scanf("%d", &select);
switch(oper){
case 1:
printf("The sum is %d\n", num1+num2);
break;
case 2:
printf("The difference is %d\n", num1-num2);
break;
case 3:
printf("The quotient is %d\n", num1/num2);
break;
case 4:
printf("The product is %d\n", num1*num2);
break;
case 5:
printf("The remainder is %d\n", num1%num2);
break;}
}while(select == 1);
} ```
I think you want something like bellow code.
Try this:
#include <stdio.h>
int main()
{
int num1, num2, oper, select;
do{
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter the number 1-5 to for the operations\n");
printf("1-Addition\n");
printf("2-Subtraction\n");
printf("3-Division\n");
printf("4-Multiplication\n");
printf("5-Modulo\n");
scanf("%d", &oper);
switch(oper){
case 1:
printf("The sum is %d\n", num1+num2);
break;
case 2:
printf("The difference is %d\n", num1-num2);
break;
case 3:
printf("The quotient is %d\n", num1/num2);
break;
case 4:
printf("The product is %d\n", num1*num2);
break;
case 5:
printf("The remainder is %d\n", num1%num2);
break;
}
printf("Press 0 to stop and 1 to continue: ");
scanf("%d", &select);
} while(select == 1);
printf("Finish");
}
change the following code bellow:
while(select != 0);
Try this:
#include <stdio.h>
int main()
{
int num1, num2, oper, select;
printf("Enter the first number:");
scanf("%d", &num1);
printf("Enter the second number:");
scanf("%d", &num2);
printf("Enter the number 1-5 to for the operations\n");
printf("1-Addition\n");
printf("2-Subtraction\n");
printf("3-Division\n");
printf("4-Multiplication\n");
printf("5-Modulo\n");
scanf("%d", &oper);
do{
printf("Press 0 to stop and 1 to continue");
scanf("%d", &select);
switch(oper){
case 1:
printf("The sum is %d\n", num1+num2);
break;
case 2:
printf("The difference is %d\n", num1-num2);
break;
case 3:
printf("The quotient is %d\n", num1/num2);
break;
case 4:
printf("The product is %d\n", num1*num2);
break;
case 5:
printf("The remainder is %d\n", num1%num2);
break;
}
}while(select != 0);
}

Repeat the c program according to user

I want this program to repeat every time when users wants to continue.
I want user to choose "yes" to continue the program using other options but it's not executable. I used 'if else' statement for that but I am not getting any applicable or satisfying results. Can someone help me on this matter?
#include <stdio.h>
int main() {
float a, b;
int p;
char q;
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo u want to continue:(y for yes and n for no) :");
scanf("%c", &q);
if (q == 'y')
return main();
else
return 0;
}
You need to use a loop for this. Explanations in the comments:
int main() {
float a, b;
int p;
char q;
do // use a loop here
{
printf("Enter the first number:");
scanf("%f", &a);
printf("Enter the second number:");
scanf("%f", &b);
printf("Choose the option:\n1.Sum\n \n2.Subtraction\n \n3.Multiplication\n \n4.Divison\n \nyour choice=");
scanf("%d", &p);
switch (p)
{
case 1:
printf("The sum of above numbers is: %f", a + b);
break;
case 2:
printf("The subtraction of above numbers is:%f", a - b);
break;
case 3:
printf("The multiplication of above numbers is:%f", a * b);
break;
case 4:
printf("The division of above numbers is:%f", a / b);
break;
}
printf("\n\nDo you want to continue: (y for yes and n for no) :");
scanf(" %c", &q); // use " %c" instead of "%c", the white space
// will absorb any blank space (including newlines)
} while (q == 'y'); // continue loop if user has entered 'y'
return 0;
}

How to make this program ask for input again if invalid input is entered (in C programming)? [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 5 years ago.
There are two different spots where the check happens.
That is, where you enter a, s, m, d, or q and when you enter the first and second number.
At any of the checks, if the check is false, it should ask you to re-enter your input.
I'm guessing this can be done by putting a scanf statement for the numbers part inside a while loop check, but when I enter an invalid value (non-number) the loop runs infinitely.
So I must be doing something wrong. I have made the a, s, m, d, and q part work for the most part.
But the second part never seems to work. For this, I left my failed attempts at the while loops out, and instead in //comments.
Any help would be greatly appreciated!
Here is my code so far:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
ch=tolower(ch);
if (ch=='\n')
continue;
else
{
switch(ch)
{
case 'a':
//The code below is what I have tried to make work.
//This code would also be copy pasted to the other cases,
//of course with the correct operations respectively being used.
//
//printf("Enter first number: ")
//while(scanf("%f",&num1)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num1);
//}
//printf("Enter second number: ")
//while(scanf("%f",&num2)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num2);
//}
//answer = num1 + num2;
//printf("%f + %f = %f\n",num1,num2,answer);
//break;
//
//I have also tried to make this work using do-while loops
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 + num2;
printf("%f + %f = %f\n",num1,num2,answer);
break;
case 's':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 - num2;
printf("%f - %f = %f\n",num1,num2,answer);
break;
case 'm':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 * num2;
printf("%f * %f = %f\n",num1,num2,answer);
break;
case 'd':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 / num2;
printf("%f / %f = %f\n",num1,num2,answer);
break;
default:
printf("That is not a valid operation.\n");
break;
}
}
}
return 0;
}
Again, thanks for any help!
Ya'll would be a life saver!
Cheers!
-Will S.
EDIT: I got my code to work! Here is the final code...
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
ch=tolower(ch);
//Ignore whitespace
if (ch=='\n')
continue;
else
{
switch(ch)
{
//Addition part
case 'a':
//First number
printf("Enter first number: ");
//Check to see if input is a number
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Second number
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Do math for respective operation
answer = num1 + num2;
//Print out result
printf("%.3f + %.3f = %.3f\n", num1,num2,answer);
break;
//Subtraction part
case 's':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 - num2;
printf("%.3f - %.3f = %.3f\n", num1,num2,answer);
break;
//Multiplication part
case 'm':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 * num2;
printf("%.3f * %.3f = %.3f\n", num1,num2,answer);
break;
//Division part
case 'd':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Check for if number is a zero
while (num2==0)
{
printf("Please enter a non-zero number, such as 2.5, -1.78E8, or 3: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
}
answer = num1 / num2;
printf("%.3f / %.3f = %.3f\n", num1,num2,answer);
break;
//For if a non-valid operation is entered
default:
printf("That is not a valid operation.\n");
break;
}
}
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
}
printf("Bye.\n");
return 0;
}
Looking back at it, I probably could do without the if/else statement.
There are multiple problems with your code. First of all in this loop
You are taking input two times on failure
while(scanf("%f",&num1)==0) //Taking Input Here Once
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1); //Again Taking input.
}
Instead what you wanted was to check the return value of the scanf() and if it was 0 you would execute the loop again, so this would be the way to do that:
int l = 0;
while(l==0){ //Checking l, if it is zero or not, if zero running loop again.
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //Storing Return Value of scanf in l
}
When the program will encounter any line with scanf("%f" , &num1) or scanf("%f" , &num2), it will skip all the white spaces and wait for next input. In the case where the input does not match the format specification, then the input isn't consumed and remains in the input buffer.
int l = 0;
while(l==0){ //Checking l
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //scanf will look at the buffer if the input
//does not match, it will not be consumed
//and will remain in buffer.
}
In other words, the character that doesn't match is never read. So when you type e.g. an a character, your code will loop indefinitely as scanf continues to fail on the same character.
When the program executes its last scanf("%f",&num2) call then because of the enter there is a newline \n character present in buffer and so due to ch = getchar(), new line \n gets stored in ch and the following if condition satisfies and the loop execute again.
if(ch =='\n')
continue;
while(scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1);
}
This loops scans two numbers per iteration. This is not what you want. Lose the second scanf.
You should also check for EOF and errors.
int result;
while((result = scanf("%f",&num1))==0)
{
printf("Invalid input. Please enter a number.");
}
if (result == EOF) .... report an error and exit ...

Not asking for char "choose" Before switch statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code executes itself without asking for char "choose" for further processing before the switch statement scanf("%c",&choose); switch(choose).
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose);
In your code if you are using any scanf before the above given code, then this behaviour is expected as the previous scanf reads the input leaving \n in the input buffer which is feeded as input to next scanf.
To overcome this issue please use fflush(stream) before scanf(...), this should solve the problem.
fflush(stdin);
or you can use getchar() function, this will alse solve your the issue.
Probably because you've already input something earlier, so that there are non-scanned characters left in the buffer which this "greedy" scanf() then scans without stopping.
You should check the return value of scanf() to learn if it succeeded or not.
And you should switch to using fgets() to read in a whole line, and then parse that. It's much safer and easier to predict, that way.
I've executed it without any problems (it gets the "choose" char):
#include <stdio.h>
int main(int argc, char *argv ) {
char choose;
float a,b,c;
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
return 0;
}
Probably its something you didn't read before...
I'm guessing that you are doing a similar "scanf("%c",&choose);" before, so the next read you will get the carriage return.
You could try to change the following lines:
scanf("%c",&choose);
for:
scanf("%c%*c",&choose);
...so you discard the \n
If this don't solve your issue, maybe you should provide more code :)

Calculator in division operation using C [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am making a calculator using C language. But the problem is that I am stuck in division.
I want that when I input 0 divided by 0, it will print undefined and if a number divided by zero will print cannot be divide by zero (which seems I got this).
Here is my code:
#include <stdio.h>
#include <math.h>
main(){
float num1, num2, total;
int a;
char choice;
clrscr();
printf("What operation you want to perform?\n 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n");
scanf("%d", &a);
switch(a) {
case 1: //Addition
printf("Addition\n Enter two numbers to be added\n");
scanf("%f%f",&num1, &num2);
total=num1 + num2;
printf("\nThe total is: %f + %f = %f\n", num1, num2, total);
printf("\nDo want to continue? Y or N: ");
scanf("%s", &choice);
if(choice=='y'||choice=='Y')
main();
else
exit(1);
break;
case 2: //Subtraction
printf("Subtraction\n Enter two numbers to be subtract\n");
scanf("%f%f", &num1, &num2);
total=num1 - num2;
printf("\nThe Difference is: %f + %f = %f\n", num1, num2, total);
printf("\nDo you want to continue? Y or N: ");
scanf("%s", &choice);
if(choice=='y'||choice=='Y')
main();
else
exit(1);
break;
case 3: //Multiplication
printf("Multiplication\n Enter two numbers to be multiplied\n");
scanf("%f%f",num1, num2);
total=num1*num2;
printf("\nThe product is: %f * %f = %f\n", num1, num2, total);
printf("\nDo you wish to continue? Y or N: ");
scanf("%s", &choice);
if(choice=='y'||choice=='Y')
main();
else
exit(1);
break;
case 4: //Division
abcd:
printf("Division\n Enter two numbers to be divide\n");
scanf("%f%f",&num1, &num2);
if(num2==0.0)
{ printf("\n %f cannot be divided by zero\n\n", num1); // ;(
goto abcd;}
else if(num1==0.0 && num2==0.0) //This is my problem here.
{printf("\nIts Undefined. 0 / 0\n\n ");
}
total=num1/num2;
printf("\nThe qoutient is %f / %f = %f\n", num1, num2, total);
printf("\nDo you want more? Y or N: ");
scanf("%s", &choice);
if(choice=='y'||choice=='Y')
main();
else
exit(1);
break;
default:
printf("Can you add letters? LOL only numbers");
printf("\nDo you want to continue? Y/N ");
scanf("%s", &choice);
if(choice=='y'||choice=='Y')
main();
else
exit(1);
break;
}
getch();
}
You have:
if(num2==0.0)
// division by zero
else if(num1==0.0 && num2==0.0)
// zero/zero is undefined
The problem is that if both numbers are 0.0, it's caught by the first test, and the second is never executed.
You need to test for both numbers being zero first, and then check whether the second number is zero.
Or you can combine the two tests:
if (num2 == 0.0) {
if (num1 == 0.0) {
// zero / zero
}
else {
// non-zero / zero
}
}
else {
// ok
}
Your if else statements are not ordered correctly.
Always try to put the case that is most specific before the more general cases.
So in your case, the specific case is when num1 == 0.0 && num2 == 0.0
Whereas the general case is num2 == 0.0
Also, your program would crash when both num1 and num2 are zero, seeing as it divides them anyway in that case.

Resources