mathcharacter

Character Arithmetic using only the Alphabet (A or a ...) in order


I am learning programming on my own at home. I'm interested in C right now and so, this is my first question. I have been trying to figure out why my code is not printing the right answer but I'm not sure what is wrong. I will attach the question and my code below. If some could help me figure out what I am doing wrong I'd be really grateful.

"Write a program that takes a string and displays it, replacing each of its letters by the letter 13 spaces ahead in alphabetical order.

'z' becomes 'm' and 'Z' becomes 'M'. Case remains unaffected.

The output will be followed by a newline.

If the number of arguments is not 1, the program displays a newline."

I'm using command line arguments to read in a string "My horse is Amazing." and the expected output should be "Zl ubefr vf Nznmvat." but I am getting this as my output "Zå ubeÇr vÇ Nznçvat."

This is my code:

#include <stdio.h>
#include <string.h>


int main(int argc, char **argv[]){

    char ch, str[100], newStr[100];
    int i, len;

    if(argc != 2){
        printf("\n");
        return (-1);
    }

    strcpy(str, argv[1]);
    len = strlen(str);

    printf("%s    %d\n\n", str, len);

    for (i = 0; i < len; i++)
    {

        ch = str[i];

        if ((ch >= 65) && (ch <= 90)){

            ch = ch + 13;

            if(ch > 90){

                ch = ch - 90;
                ch = ch + 64;
            }


        }else if ((ch >= 97) && (ch <= 122)){

            ch = ch + 13;

            if(ch > 122){

                ch = ch - 122;
                ch = ch + 96;
        }

        }
        newStr[i] = ch;

    }

    printf("%s \n", newStr);

    return 0;
}

Solution

  • ch is a signed 1-byte variable, meaning it can only represent values between -128 and 127. Adding 13 to y results in a value outside of that range.