can someone explain why (char - 'A' + key) % 26 + 'A' works for the caesar cipher?

i had to make a program using a caesar cipher and i did that but the only thing i had to google cause i couldnt figure it out was the formula for shifting the character. i know this works but can someone explain to me why it works or how someone is supposed to figure this formula out without knowing what it is? basically how do you derive this formula:

t=character being shifted
(t - 'A' + key) % 26 + 'A'

i know for a lowercase all you do is change both 'A' to 'a'
and for decripting you do (- key) instead of (+ key) and add (+ 26 right after you subract the key)

how would i have thought of this without looking it up?

thank you!!!
So.

T is the character, then you subtract 'A' to get what letter in the alphabet it is. For example A would be 0 and Z would be 25. Then you add the shift value for it (A caesar cipher is 3) so A becomes 3 and Z becomes 28. Then you do the modulus by 26 since there are 26 letters in the alphabet. This means A stays at 3 and Z changes from 28 to 2. Now we will add 'A' to them which will convert them back to letters. So A would become 3 which is D and Z becomes 2 which is C. It basically shifts the alphabet 3 characters to the left. Which means it becomes d e f g h i j k l m n o p q r s t u v w x y z a b c
thank you, i understand what the formula does now
Topic archived. No new replies allowed.