Exit case in switch in C - c

I am trying this code with exit case, the exit case doesn't work it still asks me for the two numbers and then it exits. I have provided the output. What is the alternative to the switch case that I can use for menu driven programs?
Sample input/output:
::::::Menu:::::
1. Addition:
2. Subtraction
3. Multiplication
4. Division
5. Mod
6. Exit
Enter your choice:6
Enter the values of a and b:3 4
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b,c;
int no;
do{
printf("\n::::::Menu:::::\n");
printf(" 1. Addition:\n 2. Subtraction \n 3. Multiplication \n 4. Division \n 5. Mod \n 6. Exit");
printf("\nEnter your choice:");
scanf("%d",&no);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
switch(no){
case 1:
c = a + b;
printf("\nAddition is:%d",c);
break;
case 2:
c = a - b;
printf("\nSubtraction is:%d",c);
break;
case 3:
c = a * b;
printf("\nMultiplication is:%d",c);
break;
case 4:
c = a / b;
printf("\nDivision is:%f",c);
break;
case 5:
c = a % b;
printf("\nMod is:%d",c);
break;
case 6:
exit(1);
default:
printf("\nInvalid choice\n");
break;
}
}while(no!=6);
return 0;
}

Your program asks for two numbers because you are checking for the exit code after the second scanf statement. If you wish the program to exit when 6 is entered, then you have to add an if statement in between the first and second scanf. You should additionally removed the exit case from your switch statement. Below is an example:
printf("\nEnter your choice:");
scanf("%d",&no);
if (no == 6)
exit(0);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);

You're reading the user's menu option, then asking for the next two numbers before you get to the switch statement, so of course it will always ask for those two numbers.
You need to either check specifically for 6 right after reading the menu input, or you need to move the second prompts to only where they're needed, i.e. inside each case.

It keeps asking for the two numbers because the switch statement is positioned right AFTER you ask for the user input. I restructured your code, this should work:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a,b,c;
int no;
while(1){
printf("\n::::::Menu:::::\n");
printf(" 1. Addition:\n 2. Subtraction \n 3. Multiplication \n 4. Division \n 5. Mod \n 6. Exit");
printf("\nEnter your choice:");
scanf("%d",&no);
if (no == 6)
break;
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
switch(no){
case 1:
c = a + b;
printf("\nAddition is:%d",c);
break;
case 2:
c = a - b;
printf("\nSubtraction is:%d",c);
break;
case 3:
c = a * b;
printf("\nMultiplication is:%d",c);
break;
case 4:
c = a / b;
printf("\nDivision is:%f",c);
break;
case 5:
c = a % b;
printf("\nMod is:%d",c);
break;
default:
printf("\nInvalid choice\n");
break;
}
}
return 0;
}
Note how I changed the do-while to a while-true and explicitly check for no == 6 PRIOR to asking for user input.

The statements in C are meant to be executed sequentially unless you disrupt the normal flow of action using jumps. In your case
printf("\nEnter your choice:");
scanf("%d",&no);
printf("\nEnter the values of a and b:");
scanf("%d%d",&a,&b);
// Only now does the switch start.
You ask for the choice first and then for the two numbers. That is why you always end up in entering the two values. One way is to take the exit out of the switch-case which perhaps is the simplest solution I guess. Something like
printf("\nEnter your choice:");
scanf("%d",&no);
if ( 6 == no )
exit(1);
What is the alternative to the switch case that I can use for menu
driven programs
Well, switch-case is exactly made for that. Why think of an alternative?

#include<stdlib.h>
#include<conio.h>
#include<stdio.h>
int main()
{
char ch;
while(1)
{
printf("l.print l c.print c q. exit \n");
printf("enter choice ");
scanf("%c",&ch);
switch(ch)
{
case 'l':
printf("You have typed l \n");
break;
case 'c':
printf("yoh have typed c \n");
break;
case 'q':
exit(0);
}
}
return 0;
}

Related

How Terminate the Program on Pressing Enter key in C?

i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');

Why the switch statement displays default in this C calculator?

When I run this program, it ignores everything in the switch statement, and displays the default.
I am using Code::Blocks.
Please explain to me why this logic error is encountered and maybe it is an error in Code::Blocks and not from the code — should I try it on another IDE?
#include <stdio.h>
int main()
{
double a,b;
int choose,subtract,divide;
printf("My first Calculater in c\n");
printf("\n");
printf("Enter your two numbers\n");
scanf("%lf",&a);
scanf("%lf",&b);
printf("Please choose an operation\n");
printf("1.add two no.(s)\n");
printf("2.subtract two no.(s)\n");
printf("3.multiply two no.(s)\n");
printf("4.divide two no.(s)\n");
printf("please choose an operation ");
scanf("%lf", &choose);
switch(choose){
case 1:
printf("sum of a+b is : %lf\n",(a+b));
break;
case 2:
printf("1.a-b?\n");
printf("2.b-a?\n");
scanf("%d", &subtract);
switch(subtract)
{
case 1:
printf("\ndiff of a-b is : %lf",(a-b));
break;
case 2:
printf("\ndiff of b-a is : %lf",(b-a));
break;
}
case 3:
printf("\nproduct of a*b is : %lf",(a*b));
break;
case 4:
printf("\n1.divide a/b?,a!=0");
printf("\n2.divide b/a?,b!=0");
scanf("%d", &divide);
switch(divide)
{
case 1:
if(b==0)
printf("\ndivision by zero is undefined");
else
printf("\nquotient of a/b is : %lf",(a/b));
break;
case 2:
if(a==0)
printf("\ndivision by zero is undefined");
else
printf("\nquotient of b/a is : %lf",(b/a));
break;
}
default:
printf("please choose either 1,2,3 or 4 options\n");
}
}
You are reading in a double for choose
scanf("%lf", &choose);
Change to reading a decimal
scanf("%d", &choose);

Little bit confused with the Switch Statements

I'm very new to C programming, and I need a help!
I have made a program of calculator with the help of Switch Statement and I want this program to be in a loop, So that it ask the menu (i.e Enter your Choice: Divide,Multiplication,Addition etc) again and again with the user.
Also I want, an End option with the Cases in Menu, which will close the program. I don't know how to code that End option which will make the Program Close.
Please Help!
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,choice;
float sum,mul,div,sub,quo;
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
printf("Enter the Second Number: ");
scanf("%d",&b);
printf("\n Enter Your Choice");
printf("\n\n1.Sum");
printf("\n2.Multiplication");
printf("\n3.Division");
printf("\n4.Subtraction");
printf("\n5.Quotient");
printf("\nYOUR CHOICE: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("Sum= %f\n",sum);
break;
case 2:
mul=a*b;
printf("Multiplication= %f\n",mul);
break;
case 3:
div=a/b;
printf("Division= %lf\n",div);
break;
case 4:
sub=a-b;
printf("Subtraction= %f\n",sub);
break;
case 5:
quo=a%b;
printf("Quotient= %f\n",quo);
break;
default:
printf("\n Unavailable Choice");
}
return 0;
getch();
}
Assuming you add option number 6 to close the calculator, you can add the following case to quit the program -
case 6:
// print bye message or whatever
exit(0);
break;
You can read about the exit function and what the arguments passed to it mean. Usually a 0 indicates successful exit from the program.
You also need to include stdlib.h if you want to use exit.
I would suggest introducing a loop condition variable, eg. CarryOn, initialise it to 1, and use that in a while loop. Let the loop continue as long as the variable is 1. When the user selects "End", set the variable to 0 in the case. That will end the loop.
Let me clarify it with some example code outline:
int CarryOn = 1;
while (CarryOn == 1)
{
// ...your original code
// ...
// add to switch
case 6: // 6 will be the "End" / "Exit" option
CarryOn = 0;
break;
}
You will need to have a while loop.
while(true){
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
....
//return 0; remove the return statement
getch();
}
and also add the menu item 6) Exit to your printf and handle that option as described in the one of the answers above.
case 6:
// print bye message or whatever
exit(0);
break;

do while loop in C

I am implementing a polynomial using array. This is the Problem Statement:
Write a menu-driven program to represent Polynomials as a data structure using arrays. and write functions to add, subtract and multiply two polynomials; multiply a polynomial with a constant, find whether a polynomial is a "zero- polynomial, return the degree of the polynomial. Assume that a new polynomial is created after each operation. How would you input and output polynomials?
I have created the input and output functions. But my do while loop is running twice.. Help me finding out why.
The do-while loop
do{
print_menu();
scanf("%c",&ch);
printf("\nch = %c\n",ch);
switch(ch){
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
}while(ch != 'q');
return 0;
}
The print_menu() function
void print_menu()
{
printf("\n1. Create a new polynomial.");
printf("\n2. Print polynomial.");
printf("\nq. Exit");
printf("\nEnter Choice:");
}
The create_poly() function
void create_poly(int poly[][2], int termpool[][2], int *next_poly)
{
int beg = poly[*next_poly][0];
int end, size, i, j;
printf("Enter size of the polynomial:");
scanf("%d",&size);
poly[*next_poly][1] = beg + size - 1;
end = poly[*next_poly][1];
printf("Enter terms of the polynomial(coeff then exponent):\n");
for(i=beg; i<=end; i++){
for(j=0; j<2; j++){
scanf("%d ",&termpool[i][j]);
}
}
poly[++(*next_poly)][0] = end + 1;
}
The print_poly() function
void print_poly(int poly[][2],int termpool[][2],int *next_poly)
{
int pos,beg,end;
int i;
printf("Enter position of the polynomial:");
scanf("%d",&pos);
if(pos-1 > *next_poly){
printf("Invalid position.");
return;
}
beg = poly[pos-1][0];
end = poly[pos-1][1];
for(i=beg; i<=end; i++){
printf(" %dx^%d +",termpool[i][0],termpool[i][1]);
}
printf("\b = 0");
}
Here is a sample output:
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:1
ch = 1
Enter size of the polynomial:2
Enter terms of the polynomial(coeff then exponent):
2 4
6 7
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:
ch =
Invalid choice.
1. Create a new polynomial.
2. Print polynomial.
q. Exit
Enter Choice:q
ch = q
Tried flushing the stdin… The problem stays. Printing the value of ch in each step, I think it is a whitespace. Where does the white space comes?
The answer to abnormal behavior of scanf answers this question also.
If you test the next code you will note the same problem
int main() {
char c;
do {
scanf_s("%c", &c);
if (c != 'q')
printf("test scanf() function\n");
} while (c);
}
the scanf() function works when the enter key is pressed, but this insert another char in the buffer input, the char of new line '\n', it is taken again by scanf() because the loop block. Try to change the previous code by this code:`
do {
scanf_s("%c", &c); // or c = getchar();
switch (c){
case '\n':
break;
default:
printf("test scanf() function\n");
}
} while (c);`
and will work fine. In your code only add a new case in the switch block:
switch(ch) {
case '1':
create_poly(poly,termpool,&next_poly);
break;
case '2':
print_poly(poly,termpool,&next_poly);
break;
case '\n':
break;
case 'q':
break;
default:
printf("Invalid choice.");
}
sorry, English is not my native language
There's an extra character waiting to be consumed after you make your initial choice, that's why the loop is executing twice.
See this question on the comp.lang.c FAQ

C programming do while with switch case program

I have been able to do switch case program but I want program to run again and again until a user selects to quit.
I basically wants program to run again and again using do while loop...
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
Use a do...while loop like this:
int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
{
scanf("%*[^\n]");
scanf("%*c"); //Clear the stdin
}
} while(I!=0); //Loop until `I` is not 0
This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switch in this, copy your posted code after the scanf.
The loop will run until you enter -1 as input.
#include<stdio.h>
int main()
{
int I;
do
{
puts("Enter -1 to quit");
printf("Enter your choice: ");
scanf("%d",&I);
switch(I)
{
case 1:
printf("67\n");
break;
case 2:
printf("45\n");
break;
case -1:
puts("Bye");
break;
default:
printf("default\n");
}
}while(I != -1);
return 0;
}
this program runs untill user gives input 0 or a negative number...
#include<stdio.h>
int main()
{
int I;
do
{
scanf("%d",&I);
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
}
while(I>0);
return 0;
}
Simple Use of Do-While Loop.
Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.
int choice;
do{
printf("\nHello World!"); //This is the task of the program (Replace it with your task)
printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1
// here switch will run until A is not equal to S
int N;
char A;
do{
cin>>N;
N = N%7;
cout<<endl;
cin>>A;
switch(N)
{
case 1: cout<<"Monday"<<endl; break;
case 2: cout<<"Tuesday"<<endl; break;
case 3: cout<<"Wednesday"<<endl; break;
case 4: cout<<"Thursday"<<endl; break;
case 5: cout<<"Friday"<<endl; break;
case 6: cout<<"Saturaday"<<endl; break;
case 0: cout<<"Sunday"<<endl; break;
default: cout<<"Invalid Input"; }}
while(A!='S');

Resources