Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Need help interpreting this C (programming) Code

  1. Dec 31, 2012 #1
    Code (Text):
    // Program to categorize a single character that is entered at the terminal

    #include <stdio.h>

    int main (void)

    {
         char c;

         printf ("Enter a single character:\n");
         scanf ("%c", &c);

         if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
              printf ("It's an alphabetic character.\n");
         else if ( c >= '0' && c <= '9' )
              printf ("It's a digit.\n");
         else
              printf ("It's a special character.\n");

         return 0;
    }
     
    Alright so I don't quite get the if and else if statements.

    For "else if ( c >= '0' && c <= '9' )" shouldn't that only work for single digit #s? I typed in 100, which set c=100, but the output still gave me "It's a digit." I don't understand why. 100 is >0, but not <9.
     
    Last edited by a moderator: Jan 2, 2013
  2. jcsd
  3. Dec 31, 2012 #2

    phinds

    User Avatar
    Gold Member
    2016 Award

    It's only taking the first character of what you type in, which in your example is 1
     
  4. Dec 31, 2012 #3

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    Don't "guess" the value of c that you read in. Either look at it with a debugger, or print it out.

    As PHinds said, you haven't understood what the scanf() call does.
     
  5. Jan 1, 2013 #4
    oh I see. scanf() only takes in one character b/c the input is defined as "char c."
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Need help interpreting this C (programming) Code
  1. Need Help (Replies: 2)

  2. Need help (Replies: 4)

Loading...