Need help interpreting this C (programming) Code

  • Thread starter Thread starter pyroknife
  • Start date Start date
  • Tags Tags
    Code Programming
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
pyroknife
Messages
611
Reaction score
4
Code:
// 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:
Physics news on Phys.org
pyroknife said:
I typed in 100, which set c=100.

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.
 
oh I see. scanf() only takes in one character b/c the input is defined as "char c."