Little bit confused with the Switch Statements - c

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;

Related

Infinite error loop with if/else statement in a while loop

I'm trying to make a calculator with 12 operations, the 12th being exit, and I want it to produce an error message if the user tries to input a value other than 1-12.
I got it to work for numbers like 15, 500, etc. that aren't in the range, but if the user inputs the letter 'a' for example, it results in an infinite loop, while if the user enters 500 it does what I want it to, which is print the "try again" message and display the menu again.
So, I know the problem is with the if/else loop directly contained in the while loop, but I'm not sure why it doesn't return to the menu after the break; statement in the else statement containing "red" (I put red and blue so that I could tell which statement is being printed). I tried a do/while loop but had the same issue. I also tried making the default statement in the switch case be the "try again" part, and it works if the user enters a number like 500, but as soon as a letter or character like ? is entered, I get an infinite "try again" loop.
This is the code I'm having trouble with:
#define RESTRICT(option, min, max) (option > min && option < max)
while(!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
printf("3. Show all fractions.");
printf("4. Show the absolute value.");
printf("5. Simplify.");
printf("6. Add.");
printf("7. Subtract.");
printf("8. Multiply.");
printf("9. Divide.");
printf("10. Save in archive.");
printf("11. Load in archive.");
printf("12. Exit program.");
if(scanf("%i", &option) == 1){
if(RESTRICT(option,0,12)){
switch(option){
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
case 3:
printf("Example");
break;
case 4:
printf("Example");
break;
case 5:
printf("Example");
break;
case 6:
printf("Example");
break;
case 7:
printf("Example");
break;
case 8:
printf("Example");
break;
case 9:
printf("Example");
break;
case 10:
printf("Example");
break;
case 11:
printf("Example");
break;
}
} else if (option==12){
printf("\nGoodbye!\n");
exit=1;
} else {
printf("\nThat is not an option! Try again\n");
printf("\nBlue\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
printf("\nRed\n");
break;
}
}
'a' for example, it results in an infinite loop"
'a' is never consumed by if(scanf("%i", &option) == 1){. It is not numeric text, so gets put back into stdin for the next input function. Since scanf("%i", &option) if then call again, the results repeat.
Code needs to read and consume the 'a'. Consider fgets().
Best to avoid using scanf() at all until you understand why it it bad.
According to your code, In this code scanf("%i", &option) expects interger value from the use end. when user enter non-integer value, scanf function will not store anything in the option variable. use fgets The fgets function reads a text line or a string from the specified file or console. And then stores it to the respective string variable.
Try to update your code as follows:
char input[10];
while (!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
.
.
.
fgets(input, sizeof(input), stdin);
if (sscanf(input, "%i", &option) == 1) {
if (RESTRICT(option, 0, 12)) {
switch (option) {
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
.
.
.
}
} else if (option == 12) {
printf("\nGoodbye!\n");
exit = 1;
} else {
printf("\nThat is not an option! Try again\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
}
}

Exit case in switch in 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;
}

C code, what am I missing for this control statement program?

I am working on a program. This is what I am attempting to achieve;
The program should present a menu of pay rates from which to choose. Use a switch to select the pay rate. The beginning of a run should look something like this:
If choices 1 through 4 are selected, the program should request the hours worked. The program should recycle until 5 is entered. If something other than choices 1 through 5 is entered, the program should remind the user what the proper choices are and then recycle. Use #defined constants for the various earning rates and tax rates.
This is the code I have so far, what am I missing?;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice, hour;
float taxe, total;
printf("****************************************************************\n");
printf("\nEnter the number corresponding to the desired pay rate or action");
printf("\n1)$8.75/hr");
printf("\n2)$9.33/hr");
printf("\n3)$10.00/hr");
printf("\n4)$11.20hr");
printf("\n5)Quit");
printf("**********************************************************\n");
scanf("%d", &choice);
printf("Please enter number of hours: ");
scanf("%d", &hour);
switch(choice){
case 1:
total = 8.75* hour;
break;
case 2:
total = 9.33*hour;
break;
case 3:
total = 10.00*hour;
break;
case 4:
total = 11.20*hour;
break;
case 5:
break;
return 0;
}
}
what am I missing?
What you are missing is the actual iteration.
The program should recycle until 5 is entered.
This means that you have to do all your work inside a loop, which will check each time if the value read is 5, which you need in order to stop iterating. You can use one of the following ways :
while loop:
scanf("%d", &choice);
while (choice != 5)
{
....
switch(choice){
....
}
....
scanf("%d", &choice);
}
for loop:
for (scanf("%d", &choice); choice != 5; scanf("%d", &choice);)
{
....
switch(choice){
....
}
....
}
do-while loop:
do{
scanf("%d", &choice);
....
switch(choice){
....
}
....
}while(choice != 5);
You did'nt used a loop. It can't recycle until 5 entered.
After taking the choice, insert a while loop :
while(choice != 5){
and process normally your switch, ignoring the 5 value, adding a "default" case if another value is entered.
If you want the total program to recycles, use a do{} while(); starting on your printf, ending afgter the switch.
you have yo use do while loop here like below
do
{
clrscr();
printf("****************************************************************\n");
printf("\nEnter the number corresponding to the desired pay rate or action");
printf("\n1)$8.75/hr");
printf("\n2)$9.33/hr");
printf("\n3)$10.00/hr");
printf("\n4)$11.20hr");
printf("\n5)Quit");
printf("**********************************************************\n");
scanf("%d", &choice);
printf("Please enter number of hours: ");
scanf("%d", &hour);
switch(choice){
case 1:
total = 8.75* hour;
break;
case 2:
total = 9.33*hour;
break;
case 3:
total = 10.00*hour;
break;
case 4:
total = 11.20*hour;
break;
case 5:
break;
default :
printf("\n please enter proper choice");
getch();
}
}while(choice !=5);

Terminate program in C

Could someone help me with my code?
My program isn't terminating. After choosing a brand, it should terminate but it loops forever.
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
exit(0);
}
}
return 0;
}
I guess you are misunderstanding the default case of switch: it is executed only if number is not 0,1,2,3.
If you want to exit each time a exit(0) for each case 0 1 2 3
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
exit(0);
break;
case 1:
printf("You have selected proace.\n");
exit(0);
break;
case 2:
printf("You have selected yonex.\n");
exit(0);
break;
case 3:
printf("You have selected reebook.\n");
exit(0);
break;
default:
printf("Please try again.\n");
}
}
return 0;
}
BTW a better code should be
#include<stdio.h>
int main (void)
{
int number;
bool canExit = false;
while (canExit == false)
{
canExit = true;
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
canExit = false;
}
}
return 0;
}
Replace while (count<3) with a boolean, bool loop=true; followed by while (loop). And then inside the switch when you wish to exit, don't call the exit function but simply set loop=false;.
Your break in the switch() exits the switch() but does not exit the while().
If you enter 0, default: case won't be executed.
Is it really what you wanted ?
int number=4 ;
while (number > 3)
and you can delete count, which I can't see is being used anywhere
Actually, the following structure might be better, since you won't have to put an arbitrary number in the comparison:
int number;
do {
// the thing
} while(number > 3);
In this case, it determines whether to continue the loop AFTER the first execution rather than before it. So in a do-while it will ALWAYS execute the do ONCE before the condition can break it, even if the condition is false to begin with!
I would replace your switch with:
char* brand[] = { "proace", "yonex", "reebook" };
do{
if(number == 0)
printf("exit.\n");
else if(number <= 3)
printf("You have selected %s.\n", brand[number]);
else
printf("Please try again");
}while(number > 3);
Encapsulate it in do-while loop with condition number > 3 and it will loop until user select 0-3. In this case, exit(0) is unnecessary.
You are not updating the count variable that is why it is not exiting. For exiting the while loop the count should be greater than or equal to 3.
As long as you will be giving the input 0, 1, 2 or 3 you will never reach default which has exit() and thus the program will continue to run as we have set while conditional as (count < 3) i.e. 0 < 3 which is always true. So no chance of exiting the program by while conditional. The only chance to terminate the program is from default.
So if you give input anything other than 0, 1, 2 or 3, you will reach default which will call exit() and thus will cause the program to terminate.
Hello you can exit your program by including the header file #include in your header file section.
Then you can use the exit() command
Eg :-
#inlcude<process.h>
#include<studio.h>
into opt;
printf(" enter o ");
scant(" %d",&opt);
switch(opt)
case 0: printf(" exiting the program");
getch();
exit();

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