# Pset2 Caesar wrap around result is inexplicably incorrect

I'm feeling somewhat silly about this, but for some reason whenever the inputted message in my implementation of the caesar cipher requires a wrap around, I end up with an incorrect letter in a consistent way. i.e. an input of "A" with a key of 1, 27 or 53 results in "O" instead of "B". I can't help but feel the reason for this is staring me in the face, but I can't seem to see it.

for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (isalpha(plaintext[i]) != 0)
{

// Determine if lowercase, print lower char
if ((int) plaintext[i] > 96)
{
// If text plus key is larger than alphabet
if ((int) plaintext[i] + key > 122)
{
char ciphertext = 'a' + ((plaintext[i] + key) % 26);
printf("%c", ciphertext);
}
else
{
char ciphertext = plaintext[i] + key;
printf("%c", ciphertext);
}
}
// Print upper char
else
{
// If text plus key is larger than alphabet
if ((int) plaintext[i] + key > 90)
{
char ciphertext = 'A' + ((plaintext[i] + key) % 26);
printf("%c", ciphertext);
}
else
{
char ciphertext = plaintext[i] + key;
printf("%c", ciphertext);
}

It probably works fine with 1, but the rest is an accurate description of what is happening. Your problem is here:

char ciphertext = 'a' + ((plaintext[i] + key) % 26);

Try plugging the actual numbers into this. Say that plaintext[i] is 'a' and key is 27. Here's what happens:

'a' + ((plaintext[i] + key) % 26)
= 97 + (( 97 + 27 ) % 26 )
= 97 + (( 124 ) % 26 )
= 97 + ( 20 )
= 117
= 'u'

Simply put, you can't apply modulo 26 to the ASCII value of a letter. You have to first convert any ASCII values to a number between 0 and 25 for that technique to work.

That should give you enough info to figure out how to fix this. (Remember, this is a teaching forum, so the idea is to point you in the right direction.)

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

• Ahhhh. I knew it was something simple that I simply wasn't noticing. It hadn't occurred to me that the actual ascii values were affecting the results. (Even though it was in the walkthrough.) On a technical basis my if else statement is probably unnecessary, but seemed useful while I was figuring things out. Yet again, thanks a bunch for the help. :) Sep 7 '15 at 21:34