user972306
user972306

Reputation:

How to repeat the alphabet with for loop in caesar cipher in C#

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{'.

Upvotes: 0

Views: 3236

Answers (1)

NullUserException
NullUserException

Reputation: 85468

Use modulo arithmetic:

new_pos = (current_pos + shift) % 26

current_pos has to be the relative letter position (eg: a=0, b=1... z=25). Something like:

if ('A' <= c && c <= 'Z')      // uppercase
{
    current_pos = (int) c - (int) 'A';
}
else if ('a' <= c && c <= 'z') // lowercase
{
    current_pos = (int) c - (int) 'a';
}

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.

Upvotes: 1

Related Questions