Can this if be added to this switch statement? - c

Hi so I'm building a hotel management program and I'm trying to make my switch statement short but it's not working. I tried to add a function that had the break inside but I get an error saying break not within a loop or a switch statement:
void goback()
{
char y;
printf("Would you like to go back?(Y/N)");
scanf("%c",&y);
if (y=='Y' || y=='y')
{
break;
}
}
int main(){
do
{
printf (" 1. Add a Room\n 2. Current rooms\n 3. Add a booking\n 4. Current bookings \n 5. Modify a booking\n 6. Print bill\n 7. Exit\n\n");
printf ("Which section would you like to access:");
scanf ("%d",&w);
switch (w){
case 1:
clrscr();
newroom();
goback();
case 2:
clrscr();
roomscan();
goback();
case 3:
clrscr();
addbooking();
goback();
case 4:
clrscr();
currentbooking();
goback();
case 5:
clrscr();
printf("not ready\n");
case 6:
clrscr();
printf("not ready\n");
case 7:
clrscr();
printf("\t\t\t\tLogging out... See you next time!");
exit (1);
break;
default:
printf("try again");
}
}
while (w!=7);
}

of course, you got an error because of the break; statement break you from your goback() function and not from case.
As you know each case block must end with break;.
In your case, you must put the break; statement at the end of each case block and you can make the goback() function returning a boolean to decide if you go back or not, but you must define what to do if the user does not want to go back.

I'm not sure but you might want to add breaks after your statements if they are to be executed separately and not in sequence. here I only see your case 7 contains a break, which means all cases until that one will be executed, if that's what you want it's fine, otherwise maybe try something like this
switch (w){
case 1:
clrscr();
newroom();
goback();
break;
case 2:
clrscr();
roomscan();
goback();
break;
case 3:
...
Here it seems that your goback() function tries to do that break but what it does it's it tries to break from the context where it if called, here an "if" bloc, which can't have a break inside it. That's what the compiler is saying I guess.

Related

Main Menu choice prompt is gathered even on sub Function scanf (C)

Im creating a program that has a Main Menu linked to a couple of other functions. This is the Main Menu Code
int main(){
int iMenuChoice,exit;
iMenuChoice=0;
exit =1;
while (exit !=0){
system("cls");
printf("**********Main Menu************\n");
printf("*1) Cartesian Plane *\n");
printf("*2) Number to Words *\n");
printf("*3) b *\n");
printf("*4) c *\n");
printf("*5) d *\n");
printf("*6) e *\n");
printf("*7) Exit *\n");
printf("*******************************\n");
scanf("%d",&iMenuChoice);
switch (iMenuChoice) {
case 1:
Cartisian();
break;
case 2:
Num2Word();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
system("cls");
printf("\n\nThank you for using our Program\n\n ");
exit = 0;
break;
default:
break;
}
}
getche();
}
So I test my Number to words function which prompts for a User input (Int).
But when I enter the number, The function will ask for another number (no printf prompt just a _ that waits for a number input), Lets call this mystery number X.
After the function is done converting the number, The Program will go to main menu for a split second and automatically goes to another function.
I realized that The mystery number X is somehow being used as an advance menu input! I dont know what i did wrong.
Here is the code for The num2Word function.
int Num2Word()
{
int iWor,iOnes,iTens,iHundred,iThousand;
system("cls");
printf("Enter a number(max 3000)\n");
scanf("%i \n",&iWor);
if(iWor<=3001)
{
iOnes=iWor%10;
iWor=iWor/10;
iTens=iWor%10;
iWor=iWor/10;
iHundred=iWor%10;
iWor=iWor/10;
iThousand=iWor%10;
Thousand(iThousand);
Hundred(iHundred);
if(iTens!=1)
{
Tenty(iTens);
Ones(iOnes);
}
if(iTens==1)
Exception(iOnes);
}
else{
printf("beyond 3000");
}
getche();
return 0;
}
The Tenty,Ones, Hundredth and Thousandths all use Switch, same structure as code below:
int Ones(int x)
{
if(x!=0){
switch(x)
{
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
case 4:
printf("Four ");
break;
case 5:
printf("Five");
break;
case 6:
printf("Six");
break;
case 7:
printf("Seven");
break;
case 8:
printf("Eight");
break;
case 9:
printf("Nine");
break;
default:
break;
}
}
return;
}
Since I cant post images yet ill try to show how the function output looks like
Enter a Number (Max 3000):
619
//I press enter here and nothing happens
3 //I must input another number for it to show the conversion, in this case number 3.
six hundred nineteen
After this, itll go back to main menu for a split sec and go straight to Main() Switch(iMenuChoice) Case 3.
There's no mystery number X or ghost :)
Change
scanf("%i \n",&iWor);
to
scanf("%i",&iWor);
The whitespace characters you have in the format string of scanf, ignores all whitespace characters. That's why you are forced to input a non-whitespace character.
I realized that The mystery number X is somehow being used as an
advance menu input! I dont know what i did wrong.
There is no mystery number X. The problem in your code is this line:
scanf("%i \n",&iWor);
This scanf ignores white-space characters. When a white-space character is specified as directive in scanf. This directive maches any amount of white space, including none, in the input. That's why you have to insert the second "mysterious" value. According to scanf documentation a white space character is a sequence of white-space characters (space, tab, newline etc.; see isspace(3)).
To solve the issue, you can just %i directive. For example:
scanf("%i",&iWor);
Docs: http://man7.org/linux/man-pages/man3/scanf.3.html

switch case in c, default before case

I was trying this :
#include<stdio.h>
int main() {
int i = 2;
switch(i) {
default:{
printf("Hi\n");}
case 1:
printf("Hi1\n");
case 2:
printf("Hi2\n");
}
}
output is "Hi2" as expected, however if i = 3,
#include<stdio.h>
int main() {
int i = 3;
switch(i) {
default:{
printf("Hi\n");}
case 1:
printf("Hi1\n");
case 2:
printf("Hi2\n");
}
}
Output is
"Hi"
"Hi1"
"Hi2"
How does program enter other cases which do not match? I know putting break in default would solve this.
Why this behavior? Is there anything mentioned in C specification for this?
In C (and many other languages) the cases are simply labels that get 'jumped' to. Once execution starts in a selected case, it flows just like normal. If you want execution to 'stop' at the end of a case 'block' you have to use the break statement (or some other flow control statement):
switch(i) {
default:{
printf("Hi\n");}
break;
case 1:
printf("Hi1\n");
break;
case 2:
printf("Hi2\n");
break;
}
}
For whatever it's worth, in my opinion this is was an unfortunate decision made by the language designers since falling through to the next case after execution one or more statements in a case are executed is very, very rarely desired. However, that's the way the language works.
C# addresses this by making it so falling out of a case is illegal - some sort of explicit flow control (a break or a goto) is required at the end of a sequence of of statements in a case (unless it's the last case in the switch).
This is because the code steps through each instruction unless explicitly stated not to.
In a switch() { }, you must be explicit.
Think about the instructions backed by this C. It would be a jump table. Without break, there would be no jump beneath each branch to go after the switch case.
Complementing #alex, try this.
#include<stdio.h>
int main() {
int i = 2;
switch(i) {
default:{
printf("Hi\n");}
case 2:
printf("Hi2\n");
case 1:
printf("Hi1\n");
}
}

My book says to make a program that tracks the amount of money a power user owes to the company using only switch statements

It had the same syntax error at all places marked with double forward slash, syntax error was "case label does not reduce to integer constant"
I can't use if statements because my book is dumb and hates if statements (but only in the switch statement chapter)
#include <stdio.h>
int main()
{
double price;
int power;
char user,hrs;
printf("Enter what kind of consumer (R for residential, C for commercial, I for industrial): ");
scanf("%c",user);
printf("Enter amount of kilowatt hours used: ");
scanf("%d",power);
switch(user)
{
case 'R':
case 'r':
price=6.00+.052*power;
break;
case 'C':
case 'c':
switch(power)
{
case (power>1000): //
price=60.00+(power-1000)*.045;
case power<=1000: //
price=60.00;
}
break;
case 'I':
case 'i':
{
printf("Hours (P for peak, O for off-peak):");
scanf("%c",hrs);
switch(hrs)
{
case 'P':
case 'p':
switch(power)
{
case power>1000: //
price=76.00+.065*(power-1000);
break;
case power<=1000: //
price=76.00;
break;
}
case 'O':
case 'o':
switch(power)
{
case power>1000: //
price=40.00+.028*(power-1000);
break;
case power<=1000: //
price=40.00;
break;
}
break;
default:
printf("Business hour ID not recognized; try again");
break;
}
}
break;
default:
printf("Consumer ID not recognized; try again");
break;
}
printf("Price is %f", price);
return(0);
}
The expressions in your case statements must be constants like 'p', not expressions like power>1000.
If you need to do expressions like power>1000, you should use if/else structures to handle all appropriate cases.
The value of a case statement must be a constant integer.
You are free to use chars (e.g. 'a', 'x', etc) because they will be converted to integers by the compiler (using their ASCII code).
Using any other type of constant will yield unexpected and probably unpleasant results.
Besides, the compiler will complain (and rightly so) if you use the same value in two different case statements. This can be trickier than it seems. For instance :
#define WHATEVER 1
switch (xxx)
{
case 1 : return 1;
case WHATEVER : return 10; // error: duplicate case value
}
Frankly I don't think your exercise is such a good illustration of the practical use of a case statement.
99% of the times, the case values will come from an enumerated type, like for instance:
typedef enum {
CMD_START,
CMD_STOP
} Command;
function process_command (Command c)
{
switch (c)
{
case CMD_START:
do_start();
break;
case CMD_STOP:
do_stop();
break;
default:
panic ("unknown command %d", c);
}
}
When you switch on power, the case targets must be constants.
Since you are actually only interested in the binary outcome of power>1000, you can apply the switch to that:
switch(power>1000)
{
case 1:
price=76.00+.065*(power-1000);
break;
default:
price=76.00;
break;
}
The exercise is meant for you to understand that using a switch this way is very close to if-else. However, only do this to satisfy an academic exercise. No one would actually want to maintain code written this way. It is more natural to use if-else:
if(power>1000)
{
price=76.00+.065*(power-1000);
}
else
{
price=76.00;
}

Switch Statement with three cases in C. Third Case is not running properly

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;
}
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.
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;
Do it like this:
case 3:
return 0;
You also might consider eliminating case 3 and just do this:
default:
return 0;
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)'
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;
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.
You just interrupt the switch case.
How about using:
case 3:
return;
break;

About switch case in C, why it does not print out? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Code before the first ‘case’ in a switch-statement
I have the following set of code in C:
void isFindValue(int value1, int value2)
{
switch (value1)
{
case 1:
printf("value1 is found!\n");
break;
case 2:
printf("value1 is found!\n");
break;
case 3:
switch(value2)
{
printf("aaaaaaaaaaaaa\n");
case 6:
printf("bbbbbbbbbbbb\n");
printf("value2 is found!\n");
break;
}
default:
break;
}
if I call the function as is isFindValue(3,6); the printf of bbbbbbbbbbbb show up, but aaaaaaaaaaaaa does not, why this will happen? should we not do something before the case?
Because switch () works using labels. It jumps to the label of which the condition is satisfied. So when reaching
switch(value2) {
printf("aaaaaaaaaaaaa\n");
case 6:
the control flow immediately jumps to the label case 6: so that it skips the call to printf().
The solution would be placing it correctly, outside of the inner switch:
case 3:
printf("aaaaa\n");
switch (value2) {
etc.
"aaaaaaaaaaaaa" is not showing up because it is misplaced (it's not contained in a label so it is unreachable). You need to move it up to before the second switch statement:
case 3:
printf("aaaaaaaaaaaaa\n");
switch(value2)
{
// body
}
The call to the printf function in the statement :
printf("aaaaaaaaaaaaa\n");
cannot be reached because it is before the first case statement of the second switch.
see Code before the first 'case' in a switch-statement
"aaaaaaaaaaaaa\n" is not being printed within any case. Your code is not properly structured.
Try moving the statement out of the switch block like this:
printf("aaaaaaaaaaaaa\n");
switch(value2)
{
case 6:
printf("bbbbbbbbbbbb\n");
printf("value2 is found!\n");
break;
}
break;
switch always look for case and that's why aaaaaaaaaaaa was skipped. It will execute the statement of related case block.

Resources