/* Puzzle S01 -- detect upper case characters */ #include <stdio.h> #include <stdlib.h> int isUppercase( int ch ) { return ch>='A' && ch<='Z' ; } int main(int argc, char *argv[]) { char trials[] = {'a', 'B', 'Z', ' ', '+', 'z', 'Z', 0x33 }; int j, ch; for ( j=0; j<sizeof(trials); j++ ) { ch = trials[j]; if ( isUppercase( ch ) ) printf("%c is upper case\n", ch); else printf("%c is NOT upper case\n", ch); } system("PAUSE"); return 0; }
Comments:
(1) The array trials[]
is an
array of char
, so sizeof(trials)
gives
the number of cells.
But this assumes that a char
is one byte.
It would be safer to use: for ( j=0; j<sizeof(trials)/sizeof(char); j++ )
(2) The int
literals in the array initializer
are truncated to fit into the cells of the array.
(3) The assignment statement ch = trials[j]
char
value in the array cell into the int
value needed for the variable.
(4) C envirnoments have
several "is" functions described in
<ctype.h>
Function |
Description |
int isalnum(int ch) | is ch alphanumeric? |
int isalpha(int ch) | is ch alphabetic? |
int isascii(int ch) | is ch in the range 0x00 to 0x7F ? |
int iscntrl(int ch) | is ch a control character? |
int isdigit(int ch) | is ch a digit? |
int islower(int ch) | is ch lower case? |
int isodigit(int ch) | Can ch be part of an octal constant? |
int isprint(int ch) | is ch a printable character? |
int isspace(int ch) | is ch a whitespace character? |
int ispunct(int ch) | is ch punctuation? |
int isupper(int ch) | is ch an uppercase character? |
int iswhite(int ch) | is ch a whitespace character? (same as isspace) |
int isxdigit(int ch) | Can ch be part of a hexadecimal constant? |
As might be expected, there are minor variations in these functions between different C environments, so you should check your documentation for exact specifications.
To increase portability of your programs, use the functions provided by the C environment rather than write your own.