ROT13 Implementation using Char Arrays

884 Views Asked by At

I'm a newbie programmer who has been working on a ROT13 implementation as part of a tutorial and came across the following code. It outputs the correct characters however I'm not quite sure how it works and there is no explanation attached.

char rot13[] = { 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M' };
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for (int i = 0; i < alphabet.length(); i++) {
    std::cout << rot13[alphabet[i] - 'A'];
}

Specifically, I dont quite understand how minusing the 'A' from a character within the string alphabet provides us with our ROT13 number. I initially thought that 'A' corresponded to an index within rot13[] and minusing that would provide us with a new index, however wouldn't that indicate that any numbers beneath A's index (Z,Y,X...) would become negative indexes as a result and throw errors.

Is anyone able to explain the logic behind this code to me?

1

There are 1 best solutions below

2
On BEST ANSWER

Granted that alphabet[i] is an uppercase letter (which is the case in your example), alphabet[i] - 'A' will compute the distance to the letter 'A' in the ASCII table. So 'A'-'A' will be 0, 'B'-'A' will be 1 and so on, up to 'Z'-'A' which is 25.

Your character array rot13 is written so that the index 0 has the letter 'N', the index 1 is the letter 'O' and so on up to index 12 with the letter 'Z' and then index 13 is 'A', index 14 is 'B' and so on up to index 25 which is 'M'

To make things clearer, let’s rewrite this line:

std::cout << rot13[alphabet[i] - 'A'];

As:

char letterBeforeRot13 = alphabet[i];
int index = letterBeforeRot13 - 'A';
char letterAfterRot13 = rot13[index];
std::cout << letterAfterRot13;

This is pretty much what your compiler does, but with more details.

If we pick an example where alphabet[i] equals to the letter 'A', letterBeforeRot13 is assigned to the letter 'A', index is assigned to 'A'-'A' which is 0, letterAfterRot13 is assigned to the element of the array rot13 at index 0, which is 'N'. So the letter 'A' is transformed into 'N'.

You can do the same for any letter and you will see that everything is fine, including the edge cases when you thought that things would be out of bounds. You cannot have negative indexes with this technique.