0

I don't understand how to write vigenere.c so for now I'm just trying to write a series of loops that, if you enter one command line argument that is a single character, will shift each character in the non encrypted message by that one letter. Even that, though, is not working. What is wrong?

// Ask user for input
string Input = GetString();

// Iterate over every character in input
int j = 0;

for (int i = 0, s = strlen(Input); i < s; i++)
{

//check is alpha?
      if (isalpha(Input[i]))
      {
           char b = Input[i];
           int k = (argv[1]);
           if (islower(b))
           {
                 b = b + k;
           }
           else if (isupper(b))
           {
                 b = b + k;
           }
           j= j + 1;
           printf("%c", b);
      }
 }
 printf("%d", j);
2
  • The line int k = (argv[1]); is not correct, please fix it so i can try the code and help you, i can fix it for myself but i wanna answer you according to your code not mine to help more efficiently. Sep 14 '14 at 3:44
  • @MichaelNageh You can make changes in your answer, just explain what you did and why. It will not be necessary for the author to change their question.
    – Air
    Sep 15 '14 at 21:45
1

In short, you are doing Caesar Cipher! Replace b = b + k from b = (((b - 'a') + k) % 26) + 'a' in case of lowercase and b = (((b - 'A') + k) % 26) + 'A' in case of uppercase.

Lets take the example of lowercase to see how it works.

Say b is any character(consider its value to be d (ASCII value 100)) and value of k to be 15, then

(b - 'a') //.....is 100 - 'a' = 100 - 97 = 3 ((b - 'a') + k) //....is 3 + 15 = 18 (((b - 'a') + k) % 26) //....is 18 % 26 = 18 (((b - 'a') + k) % 26) + 'a' //....is 18 + 'a' = 18 + 97 = 115

So the final value of b will be corresponding ASCII character of value 115 that comes out to be s. Now the question arises that why do we need %26 there? It didn't effect the value in this case . There is a simple answer, just imagine the case when the value of b - 'a' + k would exceed 26, then when you add 'a' to the leftover function, then it will go beyond 122('z') and will display non-alphabetic characters.

The whole scenario is analogous for the uppercase.

You may wish playing with this thing at Khan Academy, it will strengthen your concepts.

Another thing, we talked about Caesar Cipher here(as your query) and not a single word about Vigenere Cipher(unlike the title you mentioned).

You must log in to answer this question.

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