For whatever reason, I was just writing a Caesar recently. FWIW as something to compare with:
Code:
#include <ctype.h>
/**
* Encode text using a Caesar cipher. Only alphabetic characters are encoded,
* and in their original case (upper or lower).
*
* @param text pointer to the text to encrypt
* @param shift the number of characters to shift (must be less than 26)
*
* @return pointer to the encoded text
*
* @example
* <pre>char text[] = "All work and no play makes Jack a dull boy.";
* puts(text); // "All work and no play makes Jack a dull boy."
* puts(caesar(text, 3)); // "Doo zrun dqg qr sodb pdnhv Mdfn d gxoo erb."</pre>
*
* @note http://en.wikipedia.org/wiki/Caesar_cipher
*/
char *caesar(char *text, size_t shift)
{
static const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *start = text;
size_t i, j;
for ( i = 0; text[i]; ++i )
{
for ( j = 0; alpha[j]; ++j )
{
if ( toupper(text[i]) == alpha[j] )
{
char encoded = alpha[(j + shift) % (sizeof alpha - 1)];
text[i] = islower(text[i]) ? tolower(encoded) : encoded;
break;
}
}
}
return start;
}
(C, of course.)