My formula for vigenere is not quite right, and I'm not sure which part is wrong, could someone leave me some bread crumbs please

int j = 0;
int upperk = key[j % klen] - 'A';
int lowerk = key[j % klen] - 'a';

for (int i = 0, l = strlen(plaintext); i < l; i++)
    if (isupper(plaintext[i]))
            printf("%c", (plaintext[i] - 'A' + upperk) % 26 + 'A');
    else if (islower(plaintext[i]))
            printf("%c", (plaintext[i] - 'a' + lowerk) % 26 + 'a');

1 Answer 1


The code assumes that the case of the plaintext is the same as the case of the key. What happens when the plaintext is lowercase and the key is uppercase or vice versa? It breaks.

Calculating both upperk and lowerk is a novel approach (I kinda like it), but wouldn't it be easier to simply convert the key letter to a value between 0 and 25 inclusive and use that value later? Hint: look up the man page for toupper and tolower.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Novel but flawed. upperk and lowerk are set once before the loop and their values never change. And one value or the other will be wrong depending on whether key[0] is upper case or lower case. Jan 26, 2017 at 21:37
  • @CliffB I have amended lines 2 & 3 to: int k = key[j % klen]; and thus changed the 'upperk' and 'lowerk' in the formula and so when ciphering the plaintext, the correct case is copied across (so I haven't used toupper/tolower) but I'm getting a different output, e.g. :( encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword \ expected output, but not "ciphertext:cuxrj, yge nkrru!\n" which part of my formula is wrong? I'm lost. Thanks very much
    – Sofia
    Jan 27, 2017 at 14:33
  • @DinoCoderSaurus I have moved the amended int k variable declaration to inside the for loop above each of the printf statements
    – Sofia
    Jan 27, 2017 at 14:52

You must log in to answer this question.

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