Caesar Cipher C#

I’m currently working on the C# Caesar Cipher. When I input “hello” it is translated to kkhkhokhookhoor.

It looks like my for loop is double counting letters. I don’t understand why it is doing that and I don’t understand how to fix it.

Below is the code:

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.Write("What is your message?");

    string message = Console.ReadLine(); //End of step 1
    
    char[] secretMessage = message.ToCharArray(); //End of step 2

    char[] encryptedMessage = new char[secretMessage.Length]; //End of step 3

    for (int i = 0; i < secretMessage.Length; i++) //Step 4
    {
      char encryptLetter = secretMessage[i]; //Step 5

      int letterPosition = Array.IndexOf(alphabet, encryptLetter); //Step 6

      int secretIndex = (letterPosition + 3) % 26; //Step 7

      char newLetter = alphabet[secretIndex]; //Step 8
      
      encryptedMessage[i] = newLetter; //Step 9

      string outPut = String.Join("", encryptedMessage); 

      Console.Write(outPut); //End of Step 10
      
    }
    
      

    }

  }
}

Link to project: https://www.codecademy.com/courses/learn-c-sharp/projects/csharp-caesar-cipher

Thanks in advance for any help!

Hello, @micro6385811603, and welcome to the forums.

Generally speaking, when a loop is involved, and you’re getting more of something than you wanted, you have something inside the loop that should be outside the loop. If we were to decipher your encryption, it would read, hhehelhellhello. Notice the pattern?

Thanks for the help @midlindner, it looks like declaring the array in string outPut = String.Join(" ", encryptedMessage[i]; solved the excessive input.

1 Like