A nested if inside the switch

This is a discussion on A nested if inside the switch within the C Programming forums, part of the General Programming Boards category; here's the code(roughly of course), wondered if it can be done: Code: Case ‘2’: /*Find hourly workers salary */ Printf ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    68

    A nested if inside the switch

    here's the code(roughly of course), wondered if it can be done:

    Code:
    Case ‘2’:
    		/*Find hourly workers salary */
    	
    Printf “Please enter hours worked”
    	Scanf(%d, &hours)
    Printf (“Please enter hourly wage”)
    scanF(%d, &wage)
    	If(hours <= 40){
    	Salary_2= hours * wage
    }
    	If(Hours > 40 ){
    	Salary_2 hours * wage + hours> 40 *wage * 1.5{
    }
    Printf(“The employee’s pay is : %d” , salary_2)
    That's the gist of it, is it legal? and of not, maybe someone can suggest something. I also have a hunch the calculation for hours > 40 is wrong if anyone can tell me what that is I'd really appreciate it - math just aint working for me today
    Thanks, everyone here is a big help.
    Regards,
    Extro

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    Yes.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    68
    ok cool, thanks - but I still have a logic error. Here's the code.
    the problem is in case 2:

    Code:
    #include <stdio.h>
    int main()
    {
    
    	int pay;	
    	float salary_1;
    	float weekly_salary;
    	int hours;
    	float wage;
    	float salary_2;
    	int overtime;
    
    	printf("Please enter paycode( enter EOF to end): ");
    
    		
    
    	while (pay != 1 ){
    			switch(pay){
    		
    			case '1':	/*find managers weekly salary */
    					printf("Please enter annual salary: ");
    					scanf("%f" , &salary_1);
    					weekly_salary = salary_1 / 52;
    					printf("Salary is: ", weekly_salary);
    					break;
    
    			case '2':		/*Find hourly workers salary */
    	
    			printf("Please enter hours worked: ");
    			scanf("%d", &hours);
    			printf ("Please enter hourly wage: ");
    			scanf("%d", &wage);
    				if(hours <= 40){
    					salary_2= hours * (float)wage;
    				}
    				if(Hours > 40 ){
    					printf("Please enter overtime hours");
    					scanf("%d" , &overtime);
    
    					salary_2 = (float)salary_2 + (overtime * (float)wage * 1.5);
    }
    					printf("The employee's pay is : %d" , salary_2);
    					break;
    
    			default:
    				printf("Please enter a correct paycode.");
    				break;
    }
    	}
    
    	return 0;
    }
    How do I properly set it up to calculate overtime pay?
    Thanks,
    Extro

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    > while (pay != 1 )
    You enter the loop with pay uninitialised.

    > scanf("%d", &wage);
    It's a float, not an int - change the type, or change the conversion.
    Better yet, start using gcc and use the -Wall command line option to tell you when you mess up with printf and scanf conversions.

    > salary_2= hours * (float)wage;
    It's already a float, casting isn't going to make a bean of difference.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User cbastard's Avatar
    Join Date
    Jul 2005
    Location
    India
    Posts
    167
    You are entering the while loop with pay variable uninitialized moreover you are checking it with !=1.but you have a switch statement doing action if it has a value 1.
    You are asking user to give input for paycode but you are not taking it.You want user to enter in while loop if he has not entered EOF????if yes,declare a variable named int paycode and put scanf statment after your first input.and change while loop to while(paycode!=-1)..again put scanf statement after printf of your default statement

  6. #6
    Registered User
    Join Date
    May 2004
    Posts
    68
    Ok here's the working code I have a couple of questions about:

    Code:
    #include <stdio.h>
    int main()
    {
    
    
        int     pay;
        float   salary_1;
        float   weekly_salary;
        int     hours;
        float   wage;
        float   salary_2;
        int     overtime;
        float   wage2;
        int     weekly_sales;
        float   pay_3;
        float   sales;
        int     items;
        float   pay_4;
    
    
    	printf("Please enter paycode(Enter -1 to end): ");
    
    
        	while((pay = getchar()) != -1){
    			switch(pay){
    		
    			case '1':	/*find managers weekly salary */
    					printf("Please enter annual salary: ");
    					scanf("%f" , &salary_1);
    					weekly_salary = salary_1 / 52;
    					printf("Salary is: $%.2f \n ", weekly_salary);
                        break;
    
    
    			case '2':		/*Find hourly workers salary */
    	
    			printf("Please enter hours worked: ");
    			scanf("%d", &hours);
    			printf ("Please enter hourly wage: ");
    			scanf("%f", &wage);
    				if(hours <= 40){
    					salary_2= hours * wage;
    				}
    				if(hours > 40 ){
    					printf("Please enter overtime hours");
    					scanf("%d" , &overtime);
    					wage2 = wage * hours;
    
    					salary_2 = wage2 + (overtime * wage * 1.5);
    }
    					printf("The employee's pay is: $%.2f \n" , salary_2);
                                break;
                       case '3':
                       printf("Enter gross weekly sales: ");
                       scanf("%f" , &sales);
                       pay_3 = 250 + (sales * 5.7 / 100);
                       printf("This week's pay is: $%.2f" , pay_3);
                             break;
                       case '4':
                            printf("Enter number of items produced: ");
                            scanf("%d" , &items);
                            pay_4 = 250 * items;
                            printf("Amount earned: $%/2f");
                                      break;
                            case '\n':
                            break;
    
    			default:
                     printf("You have entered an incorrect paycode.");
                     printf("Please enter a correct paycode:\n");
                     break;
    }
                     printf("Please enter a paycode(Enter -1 to end): ");
    }
    
    	return 0;
    }
    The trouble is asking for another paycode, I noticed if I enter another number after it calculates pay it goes into the right case, trouble is it doesnt acutally for a paycode.
    I put in that last printf statement so it does but it displays it twice
    Any suggestions on how I might get it to ask for another paycode after the initial one has been finished?

    Thanks,
    Extro

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You should read the FAQ on getting input from a user. What's happening is when you call scanf, it leaves the newline (enter) in the input buffer. Thus, the next call to scanf reads it as its input. You should ideally use a better way to read input. If not, you should account for the newline and clear it out of the input stream before you read for use further.


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    May 2004
    Posts
    68
    I still don't understand why 'Please enter a paycode(Enter -1 to end): ' would come up twice one immediately following the other when its done the first case, like this:
    Please enter a paycode(Enter -1 to end): Please enter a paycode(Enter -1 to end):

    Why is it doing this?
    Thanks,
    Extro

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    while((pay = getchar()) != -1){
        switch(pay){
            case '1':	/*find managers weekly salary */
                ...
            break;
    
            case '2':		/*Find hourly workers salary */
                ...
            break;
    
            case '3':
                ...
            break;
    
            case '4':
            break;
    
            case '\n':
            break;
    
            default:
                printf("You have entered an incorrect paycode.");
                printf("Please enter a correct paycode:\n");
            break;
        }
        printf("Please enter a paycode(Enter -1 to end): ");
    }
    Well for starters, 'getchar' isn't going to return -1 ever. The 'getchar' function returns a keystroke (not entirely accurate, but close enough). What single key on your keyboard is '-1'?

    Ok, now let's examine the loop itself:
    Code:
    while the key read isn't something
        switch this key
            lets say we match
                oh, there's an enter left because of 'getchar'(enter)
                that skips your first scanf call
                lets say you have another, so you type 'foo'(enter)
                that stores foo
            we break from the getchar match
    
            we're out of the switch, but in the loop, so we display
            printf("Please enter a paycode(Enter -1 to end): ");
    
            (enter) from the last scanf is here
            this runs us through the loop, to the '\n' case
                all this does is 'break'
    
            we're out of the switch, but in the loop, so we display
            printf("Please enter a paycode(Enter -1 to end): ");
    That's the general idea. And there you have it, your message displayed twice, just like I said it would, for the reason I stated.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    May 2004
    Posts
    68
    Ok I fixed the code up a bit but its still not asking for another code, its just waiting for one. How do I get it to ask again?
    Thanks for all the help.
    Code:
    	
    #include <stdio.h>
    int main()
    {
    
    
        int     pay;
        float   salary_1;
        float   weekly_salary;
        int     hours;
        float   wage;
        float   salary_2;
        int     overtime;
        float   wage2;
        int     weekly_sales;
        float   pay_3;
        float   sales;
        int     items;
        float   pay_4;
    
    
    	printf("Please enter paycode(Enter EOF to end): ");
    
    
        	while((pay = getchar()) != EOF){
    			switch(pay){
    		
    			case '1':	/*find managers weekly salary */
    					printf("Please enter annual salary: ");
    					scanf("%f" , &salary_1);
    					weekly_salary = salary_1 / 52;
    					printf("Salary is: $%.2f \n ", weekly_salary);
                        break;
    
    
    			case '2':		/*Find hourly workers salary */
    	
    			printf("Please enter hours worked: ");
    			scanf("%d", &hours);
    			printf ("Please enter hourly wage: ");
    			scanf("%f", &wage);
    				if(hours <= 40){
    					salary_2= hours * wage;
    				}
    				if(hours > 40 ){
    					printf("Please enter overtime hours");
    					scanf("%d" , &overtime);
    					wage2 = wage * hours;
    
    					salary_2 = wage2 + (overtime * wage * 1.5);
    }
    					printf("The employee's pay is: $%.2f \n" , salary_2);
                                break;
                       case '3':
                       printf("Enter gross weekly sales: ");
                       scanf("%f" , &sales);
                       pay_3 = 250 + (sales * 5.7 / 100);
                       printf("This week's pay is: $%.2f" , pay_3);
                             break;
                       case '4':
                            printf("Enter number of items produced: ");
                            scanf("%d" , &items);
                            pay_4 = 250 * items;
                            printf("Amount earned: $%/2f");
                                      break;
    
                       case '\n':
                             break;
    
    			default:
                     printf("You have entered an incorrect paycode.");
                     printf("Please enter a correct paycode:\n");
                     break;
    }
    
    }
      	return 0;
    }

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    #include<stdio.h>
    
    void fflushstdin( void ) /* we write our own to flush input */
    {
        int c;
        while( (c = getchar()) != EOF && c != '\n' ); /* junk the buffered input */
    }
    
    int main( void )
    {
        int choice = 0;
    
        do
        {
            printf("Enter a character and press enter. (q to quit) :"); /* prompt */
            fflush( stdout ); /* flush the output buffer, fflush is only for output */
    
            choice = getchar( ); /* we want one character... */
            fflushstdin( ); /* after reading input, clear anything extra we don't want */
    
            printf("You entered %c.\n", choice );
        } while( c != 'q' );
    
        return 0;
    }
    Tinker with that and see if that's what you're looking for.


    Quzah.
    Hope is the first step on the road to disappointment.

  12. #12
    Registered User
    Join Date
    May 2004
    Posts
    68
    I appreciate the help but being a first year student I haven't yet been taught things like fflush so IU'm not sure how to work with it. I went with a do...while and I'm still getting
    Please enter paycode(Enter EOF to end):Please enter paycode(Enter EOF to end):
    everytime it loops through

    Code:
    #include <stdio.h>
    int main()
    {
    
    
        int     pay;
        float   salary_1;
        float   weekly_salary;
        int     hours;
        float   wage;
        float   salary_2;
        int     overtime;
        float   wage2;
        int     weekly_sales;
        float   pay_3;
        float   sales;
        int     items;
        float   pay_4;
    
    
    
        	do{
                printf("Please enter paycode(Enter EOF to end): ");
                pay = getchar();
    			switch(pay){
    		
    			case '1':	/*find managers weekly salary */
    					printf("Please enter annual salary: ");
    					scanf("%f" , &salary_1);
    					weekly_salary = salary_1 / 52;
    					printf("Salary is: $%.2f \n ", weekly_salary);
                        break;
    
    
    			case '2':		/*Find hourly workers salary */
    	
    			printf("Please enter hours worked: ");
    			scanf("%d", &hours);
    			printf ("Please enter hourly wage: ");
    			scanf("%f", &wage);
    				if(hours <= 40){
    					salary_2= hours * wage;
    				}
    				if(hours > 40 ){
    					printf("Please enter overtime hours");
    					scanf("%d" , &overtime);
    					wage2 = wage * hours;
    
    					salary_2 = wage2 + (overtime * wage * 1.5);
    }
    					printf("The employee's pay is: $%.2f \n" , salary_2);
                                break;
                       case '3':
                       printf("Enter gross weekly sales: ");
                       scanf("%f" , &sales);
                       pay_3 = 250 + (sales * 5.7 / 100);
                       printf("This week's pay is: $%.2f" , pay_3);
                             break;
                       case '4':
                            printf("Enter number of items produced: ");
                            scanf("%d" , &items);
                            pay_4 = 250 * items;
                            printf("Amount earned: $%/2f");
                                      break;
    
                       case '\n':
                             break;
    
    			default:
                     printf("You have entered an incorrect paycode.");
                     printf("Please enter a correct paycode:\n");
                     break;
    }
       }
         while(pay != EOF);
      	return 0;
    }
    ...any help is appreciated more than ya know.
    Thanks,
    Extro

  13. #13
    n00b
    Join Date
    May 2005
    Location
    Lakefield
    Posts
    12
    Extro
    Just a couple of observations:

    You have declared 'pay' as an int and then go on to use it as a char

    Second; the '\n' left in the buffer is causing the second prompt for input. There is a '\n' left in the buffer after the last call for input which is being immediately assigned to 'pay' in your while statement second time through satisfying the '\n' case. While I know that it’s frowned on, using fflush(stdin) as the last line of your 'while' loop should take care of this.

    Thirdly getchar() only reads in one character, so using '-1' or 'EOF' to end your program wont work. getchar() will only load the '-' or the 'E'. Maybe scanf is a better choice.

    One novice to an other I hope this helps.


    EDIT: Missed your last post, so this refers to the code from post befor the do while change.
    Last edited by Syked4; 08-14-2005 at 09:13 AM.

  14. #14
    Registered User
    Join Date
    May 2004
    Posts
    68
    I got it to work! here's the code:
    Code:
    #include <stdio.h>
    int main()
    {
    
    
        char    pay;
        float   salary_1;
        float   weekly_salary;
        int     hours;
        float   wage;
        float   salary_2;
        int     overtime;
        float   wage2;
        int     weekly_sales;
        float   pay_3;
        float   sales;
        int     items;
        float   pay_4;
    
    
    
    
        	do{
                fflush(stdin);
                printf("Please enter paycode(Enter EOF to end): ");
                pay = getchar();
    			switch(pay){
    		
    			case '1':	/*find managers weekly salary */
    					printf("Please enter annual salary: ");
    					scanf("%f" , &salary_1);
    					weekly_salary = salary_1 / 52;
    					printf("Salary is: $%.2f \n ", weekly_salary);
                        break;
    
    			case '2':		/*Find hourly workers salary */
    	
    			printf("Please enter hours worked: ");
    			scanf("%d", &hours);
    			printf ("Please enter hourly wage: ");
    			scanf("%f", &wage);
    				if(hours <= 40){
    					salary_2= hours * wage;
    				}
    				if(hours > 40 ){
    					printf("Please enter overtime hours");
    					scanf("%d" , &overtime);
    					wage2 = wage * hours;
    
    					salary_2 = wage2 + (overtime * wage * 1.5);
    }
    					printf("The employee's pay is: $%.2f \n" , salary_2);
                                break;
                       case '3':
                       printf("Enter gross weekly sales: ");
                       scanf("%f" , &sales);
                       pay_3 = 250 + (sales * 5.7 / 100);
                       printf("This week's pay is: $%.2f \n" , pay_3);
                             break;
                       case '4':
                            printf("Enter number of items produced: ");
                            scanf("%d" , &items);
                            pay_4 = 250 * items;
                            printf("Amount earned: $%.2f \n" , pay_4);
                                      break;
    
    
    
    			default:
                     printf("You have entered an incorrect paycode.");
                     printf("Please enter a correct paycode:\n");
                     break;
    }
       }
                      while(pay != EOF);
    
      	return 0;
    }
    Last edited by Extropian; 08-14-2005 at 09:26 AM.

  15. #15
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    Wow - crazy indentation and fflush(stdin)
    1. Turn OFF tabs in your text editor, the board and everyones browser treats them differently, so it never looks good.
    2. Why you shouldn't use fflush(stdin) is in the FAQ

    Here's a sample to get you going.
    Code:
    #include <stdio.h>
    
    char *promptAndAnswer ( char *buff, size_t size ) {
      printf( "Please enter paycode(Enter EOF to end): " );
      fflush( stdout );
      return fgets( buff, size, stdin );
    }
    
    void doManager ( void ) {
      char buff[BUFSIZ];
      float salary_1,weekly_salary;
      
      printf("Please enter annual salary: ");
      fflush( stdout );
      fgets( buff, sizeof(buff), stdin );
      sscanf( buff, "%f", &salary_1 );
      weekly_salary = salary_1 / 52;
      printf("Salary is: $%.2f\n", weekly_salary);
    }
    
    void doWorker ( void ) {
      printf( "doWorker\n" );
    }
    
    int main ( ) {
      char buff[BUFSIZ];
    
      while ( promptAndAnswer( buff, sizeof(buff) ) != NULL ) {
        char pay = buff[0];
        switch ( pay ) {
          case '1':
            doManager();
            break;
          case '2':
            doWorker();
            break;
          default:
            printf( "Not valid\n" );
            break;
        }
      }
      return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Nested array vs. tree
    By KONI in forum Tech Board
    Replies: 1
    Last Post: 06-07-2007, 04:43 AM
  2. Nested Classes
    By manofsteel972 in forum C++ Programming
    Replies: 4
    Last Post: 11-21-2004, 10:57 AM
  3. unwanted number in switch
    By chrismax2 in forum C++ Programming
    Replies: 5
    Last Post: 04-24-2004, 05:43 AM
  4. can (switch) be apart of a loop?
    By matheo917 in forum C++ Programming
    Replies: 2
    Last Post: 09-20-2001, 06:29 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21