I am making a Caesar cipher and I want to make the letters in a loop so for example if the letter ‘z’ needs to be shifted it should go back to ‘a’ for both capital and lowercase.
//Array that holds each char in the plaintext inputed is declared and initiated
char[] chars = plainTextInput.ToCharArray();
//For loop that will go through each letter and change the value of each letter by adding the shiftAmount
for (int i = 0; i < plainTextInput.Length; ++i)
{
chars[i] = (char)(((int)chars[i]) + shiftAmount);
if (chars[i] >= 97 && chars[i] <= 122)
{
if (chars[i] > 122)
{
int x = chars[i] - 123;
chars[i] = (char)((int)(97 + x));
}
}
}
//Variable for ciphertext output holds char array chars as a string
cipherTextOutput = new string(chars);
If I input 'xyz' and shift by one I get 'yz{'.
Use modulo arithmetic:
current_poshas to be the relative letter position (eg:a=0, b=1... z=25). Something like:See working demo: http://ideone.com/NPZbT
That being said, I hope this is just code you are playing with, and not something to be used in real code.