ch2-case (lowercase, uppercase)

Chapter_2     Exercise_2-2     atou Random_number_generator     Exercise_2-3







case.c     K&R, p. 43         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);
printf("upper(%s) = ", s);
upper(s);
printf("%s\n", s);

printf("Enter a word in upper case: ");
scanf("%s", s);
printf("lower(%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++)
{
if (s[i] >= 'A' && s[i] <= 'Z')
{s[i] = s[i] + 'a' - 'A';} // 'a' > 'A' in ASCII
}
}

void upper(char s[]) // to upper case
{
int i;

for (i = 0; s[i] != '\0'; i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
{s[i] = s[i] - 'a' + 'A';} // s[i] - ('a' - 'A')
}
}
/*
gcc case.c -o case
./case
Enter a word in lower case: Hello,
upper(Hello,) = HELLO,
Enter a word in upper case: World!
lower(World!) = world!
*/









Chapter_2     Exercise_2-2     atou BACK_TO_TOP Random_number_generator     Exercise_2-3



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo