prev

Selection Example

next

Source code
     #include <stdio.h>
     
     /*
      *  Program to determine whether the character typed is a number, whitespace,
      *   or something else
      */
     int main ( void ) {
       int ch;
     
       /* get a character from standard input */
       ch = getchar ();
     
       /*
        * determine what kind of character it is using an if statement
        */
     
       /* check to see if it is between the characters 0 and 9 */
       if ( ch >= '0' && ch <= '9' )
         printf ( "if: character '%c' (%d) is a number\n", (char) ch, ch );
     
       /* or if it is a whitespace character */
       else if ( ch == ' ' || ch == '\n' || ch == '\t' )
         printf ( "if: character '%c' (%d) is whitespace\n", (char) ch, ch );
     
       else
         printf ( "if: character '%c' (%d) is something else\n", (char) ch, ch );
     
       /*
        * determine what kind of character it is using a switch statement
        */
       switch ( ch ) {
         case '0': 
         case '1': 
         case '2': 
         case '3': 
         case '4': 
         case '5': 
         case '6': 
         case '7': 
         case '8': 
         case '9': 
           printf ( "switch: character '%c' (%d) is a number\n", (char) ch, ch );
           break;
     
         case ' ':
         case '\n':
         case '\t':
           printf ( "switch: character '%c' (%d) is whitespace\n", (char) ch, ch );
           break;
     
         default:
           printf ( "switch: character '%c' (%d) is something else\n", (char) ch,
                    ch );
           break;
       }
         
       return ( 0 );
     }