I'm trying to write a caesar cipher program that takes an argument, converts it into an integer, and uses that as to shift the letters in a certain direction (positive numbers shift it forward and negative numbers shift it backwards. So far all the program works for all positive numbers but does not for negative numbers.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int encrypt(int character, int shift);
int main(int argc, char * argv[]) {
int shift = atoi(argv[1]);
if (shift >= 26) {
shift = ((shift + 26) % 26);
}
int character = getchar();
while (character != EOF) {
int new_character = encrypt(character, shift);
putchar(new_character);
character = getchar();
}
return 0;
}
int encrypt(int character, int shift) {
int ch = character;
int negShift = shift;
if (ch >= 'a' && ch <= 'z') {
ch = ch + shift;
if (ch > 'z') {
ch = ch - 'z' + 'a' - 1;
}
} else if (ch >= 'A' && ch <= 'Z') {
ch = ch + shift;
if (ch > 'Z') {
ch = ch - 'Z' + 'A' - 1;
}
}
return ch;
}