1

My objective is to insert text in a box, choose a value to be the shifting value on the alphabet and to get the encrypted output.

I'm just starting with C# and i found this exercise. This is what i came up with, which is certanly wrong because when I run it I get this error message "An unhandled exception of type 'System.IndexOutOfRangeException' occurred". I know where the error is but I don't know how to fix it. I'd like to know what I' doing wrong or even if the way I'm doing this is right.

Thank you in advance!

private void cifrar_Click(object sender, EventArgs e)
    {
        string input = message.Text;

        int shift = int.Parse(shifting.Text);

        char[] alphabet = new char[26] { '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' };

        string output_text = "";

        char[] input_array = input.ToCharArray();

        for (int i = 0; i < alphabet.Length; i++)
        {
            for (int j = 0; j < input_array.Length; j++)
            {
                if (input_array[j] == alphabet[i])
                    input_array[j] = alphabet[i + shift];
            }                    
        }

        output_text = new string(input_array);

        output.Text = output_text;
    }

    }

}

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Diogo Carvalho
  • 255
  • 1
  • 7
  • 15

1 Answers1

2

When adding shift to i you can get a new value that is higher than the number of elements in the array. Trying to access the array with this index will result in the IndexOutOfRangeException.

Limit the index to be within the valid range by using the modulo operator.

input_array[j] = alphabet[(i + shift) % alphabet.Length];

You also need to change the logic a bit:

for (int j = 0; j < input_array.Length; j++)
{
    for (int i = 0; i < alphabet.Length; i++)
    {
        if (input_array[j] == alphabet[i])
        {
            input_array[j] = alphabet[(i + shift) % alphabet.Length];
            break;
        }
    }
}                    

I swapped the inner and outer loop and also added the break statement. This is necessary so that the cipher is not applied multiple times to the same position in the input string.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
  • It doesn't give me the error message anymore, but the output is wrong. Example: shift value = 2 Input = Hi Output I'm getting = Bi It should be "Jk" – Diogo Carvalho Mar 05 '17 at 17:20
  • @DiogoCarvalho because you only check for uppercase letters. Lowercase letters are not modified. Convert your input to uppercase first. – NineBerry Mar 05 '17 at 17:22
  • even if I put the input "HI" the output is wrong. It's giving me "BA". But yes, I also forgot to convert the input, thanks – Diogo Carvalho Mar 05 '17 at 17:25
  • I copy pasted your code and that's what I'm getting. Input HI is giving me the output BA – Diogo Carvalho Mar 05 '17 at 17:26