Thread: Replacing switch statement with a nested if/else

  1. #1
    Registered User
    Join Date
    Aug 2010
    Posts
    8

    Replacing switch statement with a nested if/else

    I have to replace the switch statement with a nested if/else of this program:

    Code:
    #include <stdio.h>
    
    int main()
    {
       int grade;
       int aCount = 0, bCount = 0, cCount = 0, 
           dCount = 0, fCount = 0;
    
       printf(  "Enter the letter grades.\n"  );
       printf(  "Enter the EOF character to end input.\n"  );
    
       while ( ( grade = getchar() ) != EOF ) {
    
          switch ( grade ) {    /* switch nested in while */
    
             case 'A': case 'a':  /* grade was uppercase A */
                ++aCount;         /* or lowercase a */
                break;
    
             case 'B': case 'b':  /* grade was uppercase B */
                ++bCount;         /* or lowercase b */
                break;
    
             case 'C': case 'c':  /* grade was uppercase C */
                ++cCount;         /* or lowercase c */
                break;
    
             case 'D': case 'd':  /* grade was uppercase D */
                ++dCount;         /* or lowercase d */
                break;
    
             case 'F': case 'f':  /* grade was uppercase F */
                ++fCount;         /* or lowercase f */
                break;
    
             case '\n': case' ':  /* ignore these in input */
                break;
    
             default:        /* catch all other characters */
                printf( "Incorrect letter grade entered." ); 
                printf( " Enter a new grade.\n" ); 
                break;
          }
       }
    
       printf( "\nTotals for each letter grade are:\n" );
       printf( "A: %d\n", aCount );
       printf( "B: %d\n", bCount );
       printf( "C: %d\n", cCount );
       printf( "D: %d\n", dCount );
       printf( "F: %d\n", fCount );
    
       return 0;
    }

    This is my work:

    Code:
    #include <stdio.h>
    
    int main()
    {
       int grade;
       int aCount = 0, bCount = 0, cCount = 0,
           dCount = 0, fCount = 0;
    
       printf(  "Enter the letter grades.\n"  );
       printf(  "Enter the EOF character to end input.\n"  );
    
       while ( ( grade = getchar() ) != EOF )
       {
          if ( grade == 'A' || grade == 'a' )
             ++aCount;
          else if ( grade == 'B' || grade == 'b' )
             ++bCount;
          else if ( grade == 'C' || grade == 'c' )
             ++cCount;
          else if ( grade == 'D' || grade == 'd' )
             ++dCount;
          else if ( grade == 'F' || grade == 'f' )
             ++fCount;
          else
          {
             printf( "Incorrect letter grade entered." );
             printf( " Enter a new grade.\n" );
          }
    
       }
    
       printf( "\nTotals for each letter grade are:\n" );
       printf( "A: %d\n", aCount );
       printf( "B: %d\n", bCount );
       printf( "C: %d\n", cCount );
       printf( "D: %d\n", dCount );
       printf( "F: %d\n", fCount );
    
       return 0;
    }
    I have problem with replacing the default with else. When I input grades (a,b,c,d,f) , it still print the else statement.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    It's reading the newline immediately after the grade. If you enter "a", the input buffer has "a\n", so add another getchar() just before the if/else (and don't do anything with the value...just ignore it) to eat the newline.

  3. #3
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Or you can do "fflush(stdin);" before or after the if/else statements.
    Last edited by maxorator; 09-04-2010 at 12:38 PM.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by maxorator
    Or you can do "fflush(stdin);" before or after the if/else statements.
    You could, except that that would result in undefined behaviour.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Quote Originally Posted by laserlight View Post
    You could, except that that would result in undefined behaviour.
    Apparently the people who created the standard were not intelligent enough to realise that flushing stdin is something people often need, so most compilers fixed that stupidity for them. So it just requires people to know a little about the compiler they're using. Standards are a good thing, but once there's something that cannot be done according to the standards, it's time to spit on them.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by maxorator
    Apparently the people who made the standard were not intelligent enough to add a standard way to flush stdin
    It is simple enough to implement that without resorting to undefined behaviour, e.g.,
    Code:
    int c;
    while ((c = fgetc(stdin)) != EOF && c != '\n');
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Quote Originally Posted by laserlight View Post
    It is simple enough to implement that without resorting to undefined behaviour, e.g.,
    Code:
    int c;
    while ((c = fgetc(stdin)) != EOF && c != '\n');
    Quote from FAQ about this:
    Quote Originally Posted by FAQ
    If you are sure that unwanted data is in the input stream, you can use some of the following code snippets to remove them. However, if you call these when there is no data in the input stream, the program will wait until there is, which gives you undesirable results.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Indeed, but that is not necessarily a problem since one can often determine when there is input to be discarded.

    On the other hand, we have no clue as to which compiler dev123 is using. Your suggestion is thus simply wrong, since even your "it just requires people to know a little about the compiler they're using" defense fails.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Question

    Quote Originally Posted by dev123 View Post
    I have to replace the switch statement with a nested if/else of this program:

    Code:
    #include <stdio.h>
    
    int main()
    {
       int grade;
       int aCount = 0, bCount = 0, cCount = 0, 
           dCount = 0, fCount = 0;
    
       printf(  "Enter the letter grades.\n"  );
       printf(  "Enter the EOF character to end input.\n"  );
    
       while ( ( grade = getchar() ) != EOF ) {
    
          switch ( grade ) {    /* switch nested in while */
    
             case 'A': case 'a':  /* grade was uppercase A */
                ++aCount;         /* or lowercase a */
                break;
    
             case 'B': case 'b':  /* grade was uppercase B */
                ++bCount;         /* or lowercase b */
                break;
    
             case 'C': case 'c':  /* grade was uppercase C */
                ++cCount;         /* or lowercase c */
                break;
    
             case 'D': case 'd':  /* grade was uppercase D */
                ++dCount;         /* or lowercase d */
                break;
    
             case 'F': case 'f':  /* grade was uppercase F */
                ++fCount;         /* or lowercase f */
                break;
    
             case '\n': case' ':  /* ignore these in input */
                break;
    
             default:        /* catch all other characters */
                printf( "Incorrect letter grade entered." ); 
                printf( " Enter a new grade.\n" ); 
                break;
          }
       }
    
       printf( "\nTotals for each letter grade are:\n" );
       printf( "A: %d\n", aCount );
       printf( "B: %d\n", bCount );
       printf( "C: %d\n", cCount );
       printf( "D: %d\n", dCount );
       printf( "F: %d\n", fCount );
    
       return 0;
    }

    This is my work:

    [SNIP]

    I have problem with replacing the default with else. When I input grades (a,b,c,d,f) , it still print the else statement.
    Hi, are you getting the code that uses the SWITCH from an instructor or a book? I cannot even get that to run properly. Maybe fix the code using SWITCH first, then work from that.

    [Edit #1]
    I just noticed that you're using EOF but you did not include the standard library header file.
    Last edited by Char*Pntr; 09-04-2010 at 04:56 PM. Reason: standard library not included

  10. #10
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Apparently the people who made the standard were not intelligent enough to add a standard way to flush stdin
    How to flush stdin? stdin may be redirected from your harddrive? so fflush(stdin) becomes wiping your drive?
    fflush() is for output files. When you open file with read mode, you can't modify it. So how should fflush(input_file) work?
    You could try it out yourself use fflush(stdin) and redirect stdin to a file.

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Code:
         else if ( grade == 'F' || grade == 'f' )
             ++fCount;
          else
          {
             printf( "Incorrect letter grade entered." );
             printf( " Enter a new grade.\n" );
    You still need "else if" for your final clause.

  12. #12
    Registered User
    Join Date
    Jun 2010
    Location
    Michigan, USA
    Posts
    143
    Quote Originally Posted by CommonTater View Post
    Code:
         else if ( grade == 'F' || grade == 'f' )
             ++fCount;
          else
          {
             printf( "Incorrect letter grade entered." );
             printf( " Enter a new grade.\n" );
    You still need "else if" for your final clause.
    Why do you think so? Are you saying this for all
    Code:
    if (...) {...} else if (...) {...} ... else {...}
    sequences or is there something specific about this one?

  13. #13
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Unhappy

    Quote Originally Posted by CommonTater View Post
    Code:
         else if ( grade == 'F' || grade == 'f' )
             ++fCount;
          else
          {
             printf( "Incorrect letter grade entered." );
             printf( " Enter a new grade.\n" );
    You still need "else if" for your final clause.
    Just curious, did you try to compile the change with your suggestion? When I read this,
    I went scrambling back around 5 chapters in my C book to check this out. There I found out, that with multiple "else if" the last part of that structure ends with just an "else".

  14. #14
    Registered User Char*Pntr's Avatar
    Join Date
    Sep 2007
    Location
    Lathrop, CA
    Posts
    198

    Unhappy

    Quote Originally Posted by dev123 View Post
    I have to replace the switch statement with a nested if/else of this program:
    If this is so, you can't do this because the code using switch() (the logic) is fatally flawed as well.

    What blows my mind, is this assignment. The switch() code was designed to replace ugly code using too many ifs and else if conditions. The switch() code can turn ugly code into one of elegance and simplicity.

    The assignment should have had you take a long if - else if structure and change it to using a switch construction.

    The premise of the argument, "take this switch() code and convert it to code using if - else if" construction is false on the basis that the switch () code presented above is also fatally flawed.

    Specifically, I take issue with:

    Code:
    while ( ( grade = getchar() ) != EOF )
    and the rational behind this design.

    I'd like to see the algorithm or pseudo code. I would not have taken a trivial task, such as summing different grades, and then printing out the result, as presented.

  15. #15
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I won't even use switch.
    Code:
    if( strchr("abcdef",tolower(grade)) ) {
    Count[ tolower(grade) - 'a' ];   
    } else {
     ...
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Switch statement / default:
    By kcpilot in forum C Programming
    Replies: 4
    Last Post: 12-02-2008, 03:14 PM
  2. Getting the switch statement to work.
    By mtymightymike in forum C Programming
    Replies: 7
    Last Post: 10-15-2008, 06:32 PM
  3. Stack operations from switch statement elements
    By mlsrar in forum C Programming
    Replies: 15
    Last Post: 10-02-2008, 01:12 PM
  4. Switch Statement
    By DarkDot in forum C++ Programming
    Replies: 11
    Last Post: 03-28-2007, 10:11 PM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM