• Status: Solved
• Priority: Medium
• Security: Public
• Views: 290

# how do I move from case to case in a switch statement?

I was writing a program that was calculating wage and here is a snippet from it. The test expression of the switch statement is hours < 40, and when a number less than 40 was entered the switch statement worked fine. But when a number larger than 40 was entered, which I thought would direct the switch statement to case 0, nothing happened. Any idea why case 0 isn't be considered the "false" result of hours < 40, as I expected?
``````printf("How many hours did you work? (enter q to quit)\n");
while(scanf("%d", &hours))
{
printf("What was your hourly wage?\n");
scanf("%f", &rate_pr_hr);
switch (hours < 40)
{
case 1:
case 0:
``````
0
prebek
• 3
• 2
• 2
• +2
1 Solution

Commented:
it looks like case 1: and case 0: are labels on the same (missing) code, so what go you expect to happen differently?
0

Author Commented:
i didn't include the code, i just wanted to point out that case 1 worked and case 0 didn't. But here is the code:

#include <stdio.h>

int main ()
{

float rate_pr_hr;
int hours;
float pay;

printf("How many hours did you work? (enter q to quit)\n");
while(scanf("%d", &hours))
{
printf("What was your hourly wage?\n");
scanf("%f", &rate_pr_hr);
switch (hours <= 40)
{
case 1:
pay = hours * rate_pr_hr;
printf("You made \$%f last week\n\n", pay);
break;
default:
pay = 40 * rate_pr_hr + ((hours - 40) * rate_pr_hr * 1.5);
printf("You made \$%f last week\n\n", pay);
break;
}
printf("How many hours did you work?\n");
}

printf("Bye.\n\n");
return 0;
}
0

Commented:
I don't see a case 0: in that code, but when (hours <= 40) is not 1, it goes to the default: label
0

Commented:
put
case 0:  instead default:
0

Commented:
case 0:  instead default: should make no difference here, since when (hours <= 40) is not 1, it will be 0
0

Commented:
what does your system kick back from

int temp = (hours <= 40);
printf("%d\n", temp);

when hours = 40 and hours > 40?
0

Commented:
Wouldn't an if statement be more appropriate here ?
``````if (hours <= 40) {
pay = hours * rate_pr_hr;
}
else {
pay = 40 * rate_pr_hr + ((hours - 40) * rate_pr_hr * 1.5);
}
printf("You made \$%f last week\n\n", pay);
``````
0

Commented:
Probably would be better programming practice Infinity08 as it doesn't require the compiler to convert the output of a boolean operation to integer as is obviously tricky, but that's not nearly as fun :P Besides, I ran this code and got the expected behavior (40 hrs at \$10 got \$400 and 50 hrs at \$10 got \$550) so it's safe to assume it's how the compiler is handling the statement.
0

Author Commented:
you guys are correct, i changed default to case 0 and the program worked fine. thanks.
0

## Featured Post

• 3
• 2
• 2
• +2
Tackle projects and never again get stuck behind a technical roadblock.