Need help interpreting this C (programming) Code

  • Thread starter pyroknife
  • Start date
  • #1
613
3

Main Question or Discussion Point

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:

Answers and Replies

  • #2
phinds
Science Advisor
Insights Author
Gold Member
2019 Award
16,185
6,194
It's only taking the first character of what you type in, which in your example is 1
 
  • #3
AlephZero
Science Advisor
Homework Helper
6,994
291
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.
 
  • #4
613
3
oh I see. scanf() only takes in one character b/c the input is defined as "char c."
 

Related Threads on Need help interpreting this C (programming) Code

Replies
1
Views
15K
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
7
Views
2K
  • Last Post
Replies
2
Views
4K
  • Last Post
Replies
0
Views
4K
  • Last Post
Replies
0
Views
2K
  • Last Post
Replies
20
Views
10K
Replies
2
Views
1K
  • Last Post
Replies
1
Views
1K
Top