What is the logic of debugging an out of range array with the remainder operator? How does the % keep it from going out of range?

Viewed 49

Homework 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.

Code:

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)


for h in 0..<message.count{

  for a in 0..<alphabet.count{

    if message[h] == alphabet[a]{

      message[h] = alphabet[(a+3)%26]

      break

    }
  }
}
1 Answers

First thing, you need to know that % here means modulo in mathematics.

In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).

Example: 5 % 2 = 1 ( because remainder of 5 mod 2 = 1)

In here you use % 26 which means it will never go beyond 26 in always get the remainder which is always < 26. Beside of that your array has only 26 values which at index 0->25.

Combine both of them, that's the reason your problem which out of range is solved.

Related