Exercise 2-10 (Lower case, ternary operator)
Chapter_2 Exercise_2-9 items | Function_Precedence Chapter_3 |
Exercise 2-10 K&R, p. 52
Exercise 2-10. Rewrite the function lower(), which converts upper case letters to lower case, with a conditional expression instead of if-else.
Note: See also case.
CONTENTS: case1.c case2.c
case1.c (efficient, few function calls) download
#include <stdio.h> // for printf(), scanf()
#define LENGTH 100 // max word length
void lower(char []); // to lower case
void upper(char []); // to upper case
int main()
{
char s[LENGTH];
printf("Enter a word in lower case: ");
scanf("%s", s); upper(s);
printf("%s\n", s);
printf("Enter a word in upper case: ");
scanf("%s", s); lower(s);
printf("%s\n", s);
return 0;
}
void lower(char s[]) // to lower case
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
(s[i] >= 'A' && s[i] <= 'Z') ?
s[i] = (s[i] + 'a' - 'A') : 1; // 'a' > 'A' in ASCII
} // compiler requires an expression after : (1 is an expression)
}
void upper(char s[]) // to upper case
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
(s[i] >= 'a' && s[i] <= 'z') ?
s[i] = (s[i] - 'a' + 'A') : 0; // s[i] - ('a' - 'A')
} // compiler requires an expression after : (0 is an expression)
}
/*
gcc case1.c -o case1
./case1
Enter a word in lower case: Hello,
HELLO,
Enter a word in upper case: World!
world!
*/
case2.c K&R, p. 43 (inefficient, too many function calls) download
#include <stdio.h> // for printf(), scanf()
#define LENGTH 100 // max word length
int lower (int c); // char to lower case
int upper (int c); // char to upper case
void lowers(char []); // string to lower case
void uppers(char []); // string to upper case
// inefficient variant (too many function calls)
int main()
{
char s[LENGTH];
printf("Enter a word in lower case: ");
scanf("%s", s); uppers(s);
printf("%s\n", s);
printf("Enter a word in upper case: ");
scanf("%s", s); lowers(s);
printf("%s\n", s);
return 0;
}
int lower (int c) // char to lower case
{
return (c >= 'A' && c <= 'Z') ?
(c + 'a' - 'A') : c; // 'a' > 'A' in ASCII
}
int upper (int c) // char to upper case
{
return (c >= 'a' && c <= 'z') ?
(c - 'a' + 'A') : c; // c - ('a' - 'A')
}
void lowers(char s[]) // string to lower case
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
s[i] = lower(s[i]);
}
}
void uppers(char s[]) // string to upper case
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
s[i] = upper(s[i]);
}
}
/*
gcc case2.c -o case2
./case2
Enter a word in lower case: Hello,
HELLO,
Enter a word in upper case: World!
world!
*/
Chapter_2 Exercise_2-9 items | BACK_TO_TOP | Function_Precedence Chapter_3 |
Comments
Post a Comment