Exercise 7-9 (isupper - Space or time efficient)
Chapter_7 Exercise_7-8 frand | ch7-Exercises Chapter_8 |
Exercise 7-9 K&R, p. 168
Exercise 7-9. Functions like isupper() can be implemented to save space or to save time. Explore both possibilities.
CONTENTS: isupper.c isuppm.c isupps.c isuppsm.c
isupper.c download
#include <stdio.h> // for printf(), getchar()
#include <limits.h> // for UCHAR_MAX
unsigned char ISUPPER[UCHAR_MAX];
int isUpper(unsigned char c);
int main() // time efficient, requires space for array
{
int c;
for (c = 0; c < UCHAR_MAX; c++)
{ // initialize array
if (c >= 'A' && c <= 'Z')
{ISUPPER[c] = 1;}
else {ISUPPER[c] = 0;}
}
printf("Give an unsigned char: ");
c = getchar();
printf("isUpper('%c'): %d\n", c, isUpper(c));
return 0;
}
int isUpper(unsigned char c)
{
return ISUPPER[c]; // one operation
}
/*
gcc isupper.c -o isupper
./isupper
Give an unsigned char: a
isUpper('a'): 0
./isupper
Give an unsigned char: B
isUpper('B'): 1
./isupper
Give an unsigned char: 1
isUpper('1'): 0
*/
Note: See Exercise_7-9 on clc-wiki-kr.
isuppm.c download
#include <stdio.h> // for printf(), getchar()
#include <limits.h> // for UCHAR_MAX
unsigned char ISUPPER[UCHAR_MAX];
#define isUpper(c) ISUPPER[c]
int main() // macro for isupper()
{
int c;
for (c = 0; c < UCHAR_MAX; c++)
{ // initialize array
if (c >= 'A' && c <= 'Z')
{ISUPPER[c] = 1;}
else {ISUPPER[c] = 0;}
}
printf("Give an unsigned char: ");
c = getchar();
printf("isUpper('%c'): %d\n", c, isUpper(c));
return 0;
}
/*
gcc isuppm.c -o isuppm
./isuppm
Give an unsigned char: a
isUpper('a'): 0
./isuppm
Give an unsigned char: B
isUpper('B'): 1
./isuppm
Give an unsigned char: 1
isUpper('1'): 0
*/
isupps.c download
#include <stdio.h> // for printf(), getchar()
int isUpper(unsigned char c);
int main() // space efficient, requires time for function call
{
int c;
printf("Give an unsigned char: ");
c = getchar();
printf("isUpper('%c'): %d\n", c, isUpper(c));
return 0;
}
int isUpper(unsigned char c)
{
return c >= 'A' && c <= 'Z'; // two operations
}
/*
gcc isupps.c -o isupps
./isupps
Give an unsigned char: a
isUpper('a'): 0
./isupps
Give an unsigned char: B
isUpper('B'): 1
./isupps
Give an unsigned char: 1
isUpper('1'): 0
*/
isuppsm.c download
#include <stdio.h> // for printf(), getchar()
#define isUpper(x) ((unsigned)((unsigned char)(x) - 'A') <= 'Z'-'A')
int main() // macro for isupper()
{
int c;
printf("Give an unsigned char: ");
c = getchar();
printf("isUpper('%c'): %d\n", c, isUpper(c));
return 0;
}
/*
gcc isuppsm.c -o isuppsm
./isuppsm
Give an unsigned char: a
isUpper('a'): 0
./isuppsm
Give an unsigned char: B
isUpper('B'): 1
./isuppsm
Give an unsigned char: 1
isUpper('1'): 0
*/
Note: See the Macro_definition_of_isupper on StackOverflow.
Chapter_7 Exercise_7-8 frand | BACK_TO_TOP | ch7-Exercises Chapter_8 |
Comments
Post a Comment