0

I have a kind of working caesarprogram but if the key is to high it prints out weird stuff. For example: key: 2 xyz prints out: zab but key: 28 xyz prints out: JKL and key: 44 prints out JKL as well. I'm already looking at the code for some time, but can still not figure out what is the problem.

Is there someone who sees the problem and can give me a hint? Thanks a lot.

Here is the piece of code where it's going wrong.

for (int i = 0, n = strlen(s)+1; i < n; i++) 
{   
    if isalpha(s[i])
    {   
    char new = (s[i]+k);

        if isupper (s[i])
        {
            if (new <= 90 && new >= 65)
            {
                printf("%c", new);
            }
            else
            {
               printf("%c", ((new-65)%26)+65);
            }
        }

        else if islower (s[i])
        {
            if (new <= 122 && new >= 97)
            {
                printf("%c", new);
            }
            else
            {
               printf("%c", ((new-97)%26)+97);
            }
        }



    }
2
  • What is k? Key?
    – i_am_david
    Aug 7, 2015 at 15:29
  • Yes, that us the key that the user gives
    – ACS
    Aug 7, 2015 at 15:54

1 Answer 1

2

You've run up against the range limit of a char. CHARs are essentially 1 byte signed integers with a range of-127 to +126. When you add 28 to 'x', the result seems like it should be 120 + 28 = 148. BUT, that's outside the range of the variable type and two's complement representation takes over (google it), so you are actually storing -108 in new.

Next, you have

((new-97)%26)+97
= (( -108 - 97) % 26 ) + 97 )
= (-205 % 26 ) + 97
= -23 + 97
= 74
= 'J'.

If you're treating a char arithmetically, you have to be careful about assigning a value > 127 to that char. Otherwise you get this problem. You can have intermediate results greater than the range of a char, as long as the assigned value is within acceptable range. For example, char x = 'a' + 1000 - 500 - 500; will work correctly. The intermediate result is over 1000, but the final result is in the range of a char. It's a trivial example, but demonstrates what works.

If this answers your question, please click on the check to accept and to remove this question from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .