Hi just needed a little bit of help with a crash im having, so im putting together a little program that will work similar to a Caesar cipher by shifting the letters by a set value, however each subsequent letter is shifted to a different letter, rather then all letters being shifted by the same value (which is easy to crack with frequency analysis).
Anyway the program works fine if the word being encoded is shorter or the same length as the code (like a 7 letter word being encoded by a 7 digit code), but as soon as you try to encode a word longer than it, it crashes with an array out of bounds error or something.
What needs to happen is it needs to loop back around to the start of the code until no more letters need encoding.
```
```
static char ZipherEncode(char input, int shift)
{
char letter = (char)(input + shift);
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
return letter;
}
static char ZipherDecode(char input, int shift)
{
char letter = (char)(input - shift);
if (letter > 'z')
{
letter = (char)(letter - 26);
}
else if (letter < 'a')
{
letter = (char)(letter + 26);
}
return letter;
}
int[] codeShift = new int[] { 4, 2, 6, 3, 0, 5, 1 };
Console.WriteLine("Please enter a word to encode: ");
string input = Console.ReadLine();
char[] zipherEncoded = new char[input.Length];
zipherEncoded = input.ToCharArray();
Console.WriteLine("\n\nENCODED: ");
int currCode = codeShift[0];
int counter = 0;
for (int i = 0; i < zipherEncoded.Length; i++)
{
if (zipherEncoded[i] != '\0')
{
//DEBUG
Console.WriteLine("WE ARE HERE!");
Console.Write("{0}", ZipherEncode(zipherEncoded[i], codeShift[i]));
}
else
{
//DEBUG
Console.WriteLine("WE ARE HERE (ELSE)!");
Console.Write("{0}", ZipherEncode(zipherEncoded[i], codeShift[currCode]));
//Console.Write("{0}", ZipherEncode(zipherEncoded[i], codeShift[counter]));
//Console.Write("{0}", ZipherEncode(zipherEncoded[i], Array.IndexOf(codeShift, currCode)));
counter++;
}
}
Console.ReadLine();
```
```
The output when I encode the word "volcano" reads - ENCODED: zqrfasp
This is correct, however when I try and encode "volcanocat", because the word is longer than the 7 digits in the code it crashes, the output should read - ENCODED: zqrfaspgcz
the "cat" part of the phrase should be encoded with a shift of 426 <<< loops back to the start of the codeShift array storing our shifts.
C (Shift of 4) > G
A (Shift of 2) > C
T (Shift of 6) > Z
As from the parts that are commented out you can see im trying to find a way to have it loop back around to the start of the shift code to finish off the final letters.
Im really new to C# so there may be a function built in to do what I want, but I cant get my head around it!
I think I cant see the forrest through the trees!