Monday, 28 October 2013

Printing a String in Uppercase (No toupper)

This seems to be a common 'to do' exercise. When I first saw this question, I always felt it shouldn't be too hard to do. And it isn't.
I posted a program to do this using toupper() to 'UPPER-CASE' each individual character (Print a String All In Uppercase), this program does not use the toupper() function, at least not the lib function, it rather uses our own toupper code.
This program will accept a string, print each character individually, if any of the characters is lower-case 'a' to 'z' (ASCII character code 97 to 122), it will be printed as the same character, but in uppercase. How?
Well, the ASCII code for 'a' is 97 and the code for 'A' is 65 (97 minus 32), 'b', code is 98, 'B' code is 98-32 (66)...and so on.
When you subtract 32 from any lower case character, you will get its upper case equivalent. That is the key.
If the ASCII code for the user entered character falls within 97 to 122 ('a' to 'z'), 32 is subtracted from it for printing: printf("%c",input[x]-32);
If it isn't no action is taken and the character is printed 'as is'.

#include <stdio.h>

int main()
{
    char input[500];
    int x=0;

    printf("Enter your string: ");
    gets(input);

    for(;;)
    {
        if(input[x]>=97 && input[x]<=122)
        {
            printf("%c",input[x]-32);
        }
        else if(input[x]=='\0') //null
        {
            break;
        }
        else
        {
            printf("%c",input[x]);
        }
        x++;
    }
    return 0;
}

No comments:

Post a Comment