I'm having trouble figuring out where/how to apply the modulo operator to the key. It seems to me that this code should work, but the output is incorrect at any letter beyond the string length of the key.

Please note that I have excluded all parts of the code that I believe to be irrelevant to the question at hand.

string encrypt = GetString();
string key = argv[1];

for (int i = 0, j = 0, k = strlen(encrypt); i < k; i++)
    j = j % k;
    printf ("%c", (((encrypt[i] - 97) + (key[j] - 97)) % 26) + 97);

1 Answer 1


If encrypt happens to be longer than key, you want to wrap around key as many times as needed to encrypt your string encrypt. So when you're on the i'th character of encrypt, you want to make sure sure that if i > strlen(key), you wrap around key as needed: i%strlen(key).

Also, it does not appear from the code snippet above that you are checking for case, you need to preserve uppercase as uppercase and lowercase as lowercase.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .