# Vigenere Modulus

I'm stuck on Vigenere Cipher in pset2. I have everything working with the key and the cipher text until I need to wraparound back to the beginning of the keyword. I watched Zamyla's walk through. I understand that I need to use the modulus operator on the index of the keyword to make the shift. I do not know exactly how and where to use the modulus operator. I was thinking of adding something like the following with modulus but syntax is a weak point for me so I have been struggling with this for hours.

``````        int currentkey = key[j];
int keylength = strlen(argv);
if (currentkey == keylength)
{
key[j] = currentkey % keylength;
}
``````

I will show you an example and if you don't quite get it let me know in the comments. Here's how to use modulo to wrap around:

``````#include <stdio.h>

int main(void)
{
// let's say your key has a length of 5
int len = 5;
char* key = "hello";

for (int i = 0; i < 8; i++)
{
printf("%d - ", i % len);
printf("%c\n", key[i % len]);
}
return 0;
}
``````

Here is the output:

``````0 - h
1 - e
2 - l
3 - l
4 - o
0 - h
1 - e
2 - l
``````

In its general the modulo is the reminder of the integer division between two integers. So `7 % 2 == 1` because `7 / 2 == 3` with a reminder of 1. `10 % 4 == 2` because `10 / 4 == 2` with a reminder of 2.

• Thanks! Visually the code like this really helped. I rewrote my code and successfully completed the Vigenere Cipher! Jul 30, 2015 at 22:58

Modulus is the remainder of the division. It is primarily a mathematical operator just like multiplication. It just has the side effect of wrapping numbers around. Thus note `currentkey % keylength` is similar in syntax to `currentkey / keylength`.

Just took a look at the code as you posted in FB.

This line:

``````printf("%c", (((message[i] - 'A') + ((toupper(key[j]) - 'A') % keylength) % 26) + 'A'));
``````

keep in mind that, in this case, "j" is your index, and it's what you should keep "limited" by using % keylength. So, the idea is: First you get the correct index, then you modify it with - 'A' or anything you need to.