Modulo in Caeser Cypher

I’m able to complete, but having trouble understanding, step 12 in the Caeser Cypher.

It says that using modulo “wraps around” when you use the length of the array but I’m having trouble wrapping my head around (sorry for the pun) why this works.

Modulo is used to return a remainder when dividing a number by another correct? (i.e. 2 % 2 will return 0);

so why in:

using System;

namespace CaesarCipher
{
  class Program
  {
    static void Main(string[] args)
    {
      char[] alphabet = new char[] {'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'};
      
      Console.WriteLine("What would you like to encrypt?");
      
      string userMessage = Console.ReadLine();
      
      char[] secretMessage = userMessage.ToCharArray();
      
      char[] encryptedMessage = new char[secretMessage.Length];
      
      for (int i = 0; i < secretMessage.Length; i++) {
        
        char letter = secretMessage[i];
        
        int newLetterIndex = Array.IndexOf(alphabet, letter);
        
        newLetterIndex = (newLetterIndex + 3) % alphabet.Length;
        
        char newLetter = alphabet[newLetterIndex];
        
        encryptedMessage[i] = newLetter;
                 
      }
      
      Console.WriteLine(String.Join("", encryptedMessage));
    }
  }
}

does the module make my newLetterIndex variable “wrap around”?

Hello, @cuppettk.

Welcome to the forums!

Consider what happens with the letter ‘z’. The index of ‘z’ is 25. Add 3 to 25, and you get 28. Perform the modulo operation: 28 % 26, and you get 2. The letter at index 2 is ‘c’ which is exactly what we want. :slightly_smiling_face:

P.S. For future posts including code, please refer to this: How do I format code in my posts? Following the guidelines in the link will make your code appear as it does now.

@midlindner Thank you for the help. This sort of answered my question. I can see the logic of using it to reach an index of 2 so that was helpful.

What I was maybe more confused about was how all the other letters before x were accessible if you were using modulo to come up with the index.

The answer to that (which you did lead me to with your response so thank you :smile:) ), is that when using modulo with a number less than itself (i.e. 25 % 28), then it returns the original value because it is not divisible by the modulus at least once, therefore the remainder is the whole of the original value. (this is from what I understand using google)

I will be more careful to format my code from now on!

1 Like