I'm stuck halfway in vigenere. This is some of my code.

enter image description here

When I tried to work that out, something went wrong.

enter image description here

Kindly appreciate any help.


You shouldn't consume any characters from key if the current character in text in non-alphabetical character. The variable i increases anyway whether the current character in text is alphabetical or not. Maybe you should calculate the index of the current character in key using a different separate variable.

Edit 0: given the string "Meet me at the park at eleven am" as text and the keyword "bacon" as key, here's how key should repeat

Meet me at the park at eleven am
baco nb ac onb acon ba conbac on


Meet me at the park at eleven am

Edit 1: After debugging your code, it turns out you have 2 main issues

  1. you should be having this loop

    for (int j = 0 ; j < k ; j++)

    because we don't really need to iterate k times each time we encrypt an alphabetical char from text. Instead, j should be declared separately maybe in the header of the main for loop like that

    for (int i = 0, j = 0  ; i < n  ; i++ )

    Also, keep in mind that j should be incremented by 1 if and only if an alphabetical char from text is encrypted.

  2. your conditions

    if (isupper(key[i]))


    if (isupper(key[i]))

    we really shouldn't use key[i] here because i is incremented anyway and it doesn't represent the index of the current key at all. Also, i itself might be beyond the array (i.e., the string key) boundaries at this moment if the plaintext is longer than the key. And that's what caused the "ef" from "abcdef" to get encrypted to "ln" respectively instead of "fh" using "abc" as key as we expected because key[i] is a garbage value. Since isupper() checks a garbage value in this case which happens to be an ASCII value of an uppercase character, this makes the wrong condition gets executed.

To fix that, simply, check key[j % k] instead of key[i].

Hope that helps!

  • But, how to skip the keyword? – MDUM Aug 9 '14 at 12:19
  • @MDUM I've just edited my answer with an example of what I meant. Please look at the Edit section! – kzidane Aug 9 '14 at 12:47
  • And one more thing. For abcdef, it turns out to be acedln. I really have no idea what happened over there. – MDUM Aug 9 '14 at 13:31
  • @MDUM I'm sorry I don't get that! Can you please rephrase your question? – kzidane Aug 9 '14 at 14:31
  • Back to the posted question. I tried to put in my plaintext 'abcdef', and it ciphered 'acedln'. – MDUM Aug 9 '14 at 14:38

You must log in to answer this question.

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