How to Wrap Around Array Indexes?

I have the Vigenere encryption portion working properly, but can't seem to figure out how to wrap around argv indexes.

My first for loop declared two ints, i and j, and incremented each int with each iteration.

I then included an if statement where if j is greater or equal to the strlen of argv then it would set j back to 0. If not, it would proceed with the encryption.

The code compiles but does not encrypt properly when the strlen of argv is less than the input.

Can someone offer help on this?

and welcome to the SE community. As for your question, here goes the answer:

This is really simple, to do so, use the modulus operator, i.e. the % operator.

Te modulus operator returns the remainder when you divide one number by the another, for example, if you perform 200 % 82, it would return 36, in the same way, 100 % 100 would give 0 and so on. Now that you know how toi use the modulus operator, use this operation to ensure that the character which is used for the cipher never crosses the lenght of the keyword. Best of luck, and I leave the job of implementing this function in the operator to you, so best of luck.

Happy Coding!

• Thanks Nib! My initial thought when approaching this was to use the modulus operator, but I had some difficulty which so I tried an alternative solution of setting the increment counter back to 0. I took your suggestion and revisited using the modulo, but still a bit stuck. I figured out that you need to modulo by the strlen of argv, however when I write: (text[i])-97)+argv[i%l]-97)%26)+97)) with int l being the strlen, it still doesn't seem to work. Logically, it seems like it should as every time argv[i] becomes greater than the strlen, it uses the remainder... Jun 21 '14 at 19:50

Usually the remainder operator (i.e., %) is used for wrapping around something. The reason is simply because, mathematically, the remainder of dividing an integer a over an integer b is from 0 to b - 1.

Meanwhile, if we have an array of size 5 (indexes: 0, 1, 2, 3, 4). Given x, an integer >= 0, we can securely get a valid index in our 5-element array in terms of x using this formula:

current index = x % array size

This way, we guarantee that x will be in [0 - 4] since the size is 5.

• How to get the value of x?? should we make another loop or use just the int i value of the loop for the string passed to be encrypted. Jan 29 '15 at 8:46
• @Birat or just create another variable to keep track of that and increment it inside your loop as needed ;)
– kzidane
Jan 29 '15 at 10:51

If you want to wrap negatively aswell

(arrayIndex + arrayLength) % arrayLength

+ arrayLength first turns a negative index positive.