# vigenere cipher formula

I am having trouble with the cipher formula. I am working on just getting lowercase character right using the keyword "bacon" and plain text string "test". I get a result of "nxna". Any help is appreciated. Here is the relevant code.

``````for (int i = 0,  pl = strlen(plaintext), kl = strlen(keyword), index = 0; i < pl; i++)

{
char current = plaintext[i];

if (isalpha (current))
{
if (islower(current))

current = (current - 'a' + keyword[index % kl]) % 26 + 'a';

printf("%c" , current);

index++;
}
``````
• Quick note: Use braces with the if statements so it's clear whats being affected by the condition. Secondly, only declare and use variables in the for loop that are intrinsic to the execution of that loop. In other words, `k1` should not be defined and updated in the loop declaration. Instead it should have its own line in the for loop. Commented Aug 16, 2014 at 18:05

First of all, I got the result:
`nxnaz` instead of `nxna` (You missed a letter)

Second of all: What is wrong? Look at your code:
If the character is lower case. ``` current = (current - 'a' + keyword[index % kl]) % 26 + 'a'; ``` You seem to realize that you need to do `current - 'a'` because the ascii value for a is not '1' (or 0), but in fact 97.

However you forgot to do this for your keyword value.
Replace: `keyword[index%k1]) % 26` with `(keyword[index % kl] - 'a') % 26)`

If you're converting your plaintext letter from ASCII to position in the alphabet, you should do so with the keyword letter too.

• wow, this worked. Thank you. I really am not good at this kind of math. I can get the conceptual coding aspect generally, but math is not my strong suit. Commented Aug 16, 2014 at 19:35
• @DavidGrant You're welcome. Make sure to flag the answer as 'accepted' (The tick mark underneath the voting options on the left) when it solves your problem. (This is so other people can also see what the conclusion to the topic was) Commented Aug 16, 2014 at 19:42
• got it. thanks again. Commented Aug 16, 2014 at 19:52

The current character in your keyword should have a value in [0 - 25] too. And it's preferable to always use braces to delimit the body of an if statement.

• I am trying to figure out how to set that value. And yes, I understand about the braces. Commented Aug 16, 2014 at 19:07
• @DavidGrant well, you already did that for the current character in the plaintext. All you have to do is to apply something similar for the current character in the keyword.
– kzidane
Commented Aug 16, 2014 at 19:52