0

I am trying to fix my code for vigenere cipher. I guess there is something wrong with my if (isupper) and if else (islower) loops. I can't figure out what. First I was using two nested for loops but that was causing me trouble. So I changed my code, but still my code is not giving the expected answer. I hope someone can help me!

for(int i = 0, n = strlen(message); i < n; i++)  
{     
    char cipher[i];
    int kwlength = strlen(keyword);
    int countkey = 0;

    if (isalpha(message[i]))
    {
        int keyindex = 0;
        keyindex = (countkey % kwlength);
        // Checking lower case alphabetics.
        if (islower(message[i])) 
        {
            cipher[i] = ((message[i] - 'a') + (keyword[keyindex] - 'a')) % 26 + 'a'; 
            printf("%c", cipher[i]); 
        }
        // Checking upper case alphabetics.
        else if (isupper(message[i])) 
        {
            cipher[i] = ((message[i] - 'A') + (keyword[keyindex] - 'A')) % 26 + 'A';
            printf("%c", cipher[i]);
        }    
    countkey++;
    }        

}

1 Answer 1

2

I see two significant issues. First, you have initialized countkey inside the for loop, so it will always reset to 0 at the top of the loop.

You should move all three of the variable declarations at the beginning of the for loop to just before the loop for these reasons:

  1. declaring countkey on each pass resets it to 0 every time.
  2. While not causing a problem, recalculating kwlength on every pass through the loop is just inefficient.
  3. Each pass through the loop is creating a character array called cipher, with one more element than the previous pass. Also, the array of the previous pass is destroyed at the end of each pass. In this case, you are using cipher to process a single char, so just declare it as char cipher; before the loop, instead of as an array.

The other major problem is that your code does not handle the cases where the key and the letter to be encoded are of different case.

There may be other issues, but this will get you going.

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

1
  • Thank you! Your clear explanation really helped me!
    – Kiwi
    Commented Oct 22, 2015 at 7:27

You must log in to answer this question.

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