Solution for Exercise 13-6

ex1306

#include <stdio.h>
#include <ctype.h>

int main()
{
    char text[] = "ThiS Is a RANsom NoTE!";
    int index;
    char c;

    printf("Original: %s\n",text);
    index=0;
    while(text[index])
    {
        c = text[index];
        if(islower(c))
            text[index] = toupper(c);
        else if(isupper(c))
            text[index] = tolower(c);
        else
            text[index] = c;
        index++;
    }
    printf("Modified: %s\n",text);
    return(0);
}

Notes

* The while loop at Line 12 plows through the text as long as the character at text[index] isn't the null character at the end of the string.

* I assigned the character at text[index] to variable c at Line 14. This was done to make the following lines shorter and less complex. You could have just as easily used text[index]; the same variable can exist on both sides of the equal sign, as in this replacement for Line 16:

* The meat of the code uses the islower() and isupper() functions to compare each character in the string. When an lower or upper case character is found, it's converted by using the toupper() and tolower() functions, respectively.

* An if-else if-else structure is used to separate out each character. When a character isn't found to be lower case (Line 15), you can assume it's either upper case or a non-alphabetic character. Line 17 weeds out upper case letters. What's left falls through to Line 20.