How the remainder operator prevent it going out of index?

Problem: When the program tried to encrypt the "y" in ["c", "o", "d", "e", "c", "a", "d", "e", "m", "y"], it found its index in the alphabet, 24.

But when it looked up the letter 3 spaces to the right, which would be alphabet[27], it threw an error because the alphabet only has 26 elements! It is “out of range”.

To fix this, we can “wrap around” the alphabet by using the remainder operator: %.

On the line where we replace the current character in message, change alphabet[j+3] to alphabet[(j+3) % 26].

Now the new letter position will never go beyond 26.

Caesar’s Cipher
var alphabet: [Character] = [“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”, “j”, “k”, “l”, “m”, “n”, “o”, “p”, “q”, “r”, “s”, “t”, “u”, “v”, “w”, “x”, “y”, “z”]

var secretMessage = “codecademy”
var message = Array(secretMessage.lowercased())

for h in 0…<message.count{
for a in 0…<alphabet.count{
if message[h] == alphabet[a]{
message[h] = alphabet[(a+3)%26]

doing 27 % 26 results in 1 (since 27 is 1 more than 26)
remember that the % finds the remainder when dividing
17 % 5 would be 2 because 17 divided by 5 is 3 with 2 left over [the remainder]

So doing   % 26
should give results that are 0 to 25.

1 Like