off the top of my head
Code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char rotate_char(char c, int r)
{
int ret;
// deal with everything in upper case to make life easier
// this gets put back to the correct case later
ret = toupper(c);
// check for an invalid character
if(ret < 'A' || ret > 'Z')
{
// just return that char
return c;
}
ret += r;
// put the character back in range
while(ret < 'A')
ret += 26;
while(ret > 'Z')
ret -= 26;
// put the character in the correct case
if(islower(c))
ret = tolower(ret);
return ret;
}
int main(int argc, char *argv[])
{
char plaintext[256];
char ciphertext[256];
int len;
int rot = 0;
int i;
// get input from user
fgets(plaintext, sizeof(plaintext), stdin);
plaintext[sizeof(plaintext)-1] = '\0';
len = strlen(plaintext);
// encrypt
for(i = 0; i < len; i ++)
{
rot++;
// maximum rotation is 4 and then it repeats
if(rot > 4)
rot = 1;
// even rot is negative, odd rot is positive
// this gives the sequence +1, -2, +3, -4
if(rot % 2 == 0)
ciphertext[i] = rotate_char(plaintext[i], -rot);
else
ciphertext[i] = rotate_char(plaintext[i], rot);
}
ciphertext[len] = '\0';
printf("%s\n", ciphertext);
return 0;
}
I didn't test or compile this, but it should work.
You should put code in code tags, btw. Formatting is preserved that way.