The Caesar cipher moves every letter the same number of places along the alphabet, wrapping from Z back to A.
What to build
Read a shift and some lines of text, and print each line encrypted with that shift.
Requirements
- Shift upper-case and lower-case letters, keeping their case.
- Leave every other character (spaces, digits, punctuation) as it is.
- The shift may be negative or larger than 25; a shift of 29 is the same as 3, and −1 moves A to Z.
Input
Line 1: the shift, a whole number. Each following line: text to encrypt.
Output
Each line, encrypted.
Constraints
The shift is between −1000 and 1000. 1 to 20 lines of up to 200 characters.
Example
Input:
3
Attack at dawn!
Output:
Dwwdfn dw gdzq!
Why it works
Taking the shift modulo 26, and adding 26 before the last modulo, turns any shift into 0 to 25, so negative and large shifts both wrap correctly.
Examples
3 Attack at dawn!
Dwwdfn dw gdzq!
-1 Abc xyz
Zab wxy
Hints
Hint 1
((code - 65 + shift) % 26 + 26) % 26 + 65 handles negative shifts for upper case; use 97 for lower case.
Hint 2
Test letters with ch >= "A" && ch <= "Z".
Solution
Show one correct solution (try it yourself first)
const shift = Number(prompt());
const move = (ch, base) => String.fromCharCode(((((ch.charCodeAt(0) - base + shift) % 26) + 26) % 26) + base);
let line = prompt();
while (line !== null) {
let out = "";
for (const ch of line) {
if (ch >= "A" && ch <= "Z") out += move(ch, 65);
else if (ch >= "a" && ch <= "z") out += move(ch, 97);
else out += ch;
}
console.log(out);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step