Gaius Julius Caesar was a general and dictator of ancient Rome who lived between 100 BC - 44 BC.
When writing confidential correspondence, Caesar would encrypt his messages by replacing each letter with the third letter coming after it while wrapping around the end of the alphabet. A would become D; B would become E; C would become F; … X would become A; Y would become B; and Z would become C. To decrypt any messages, the process was reversed.
This encryption method became known as the Caesar cypher. It can be generalized to any shift of alphabet positions: one, two, four, five, etc letters to the right or the left. In this generalization, a positive key k indicates encryption should use the k-th subsequent letter and a negative key -k indicates encryption should use the k-th preceding letter. For example:
In this way, when a text is encrypted with a key k, it can be decrypted with a key of -k. Just flip the signal to decrypt.
One can use the above circles to encrypt or decrypt a text using the Caesar cypher for the keys of 3 and -12 by replacing letters on the outer circle by adjacent letters in the inner circle.
In this exercise, you should write a program that performs encryption and decryption under the Caesar cypher for an arbitrary key k.
Your program will be run with a numeric command line argument k indicating the encryption/decryption key. When k argument is not given as a command line argument, assume it to be 13.
Input will contain several lines containing the text to be encrypted or decrypted using the key k. For each line of input, output should contain the encrypted or decrypted text.
With a command line argument of 3
, i.e.: ./caesar 3
input.
Dear Julius,
Let us meet near
the Theatre of Pompey
at sundown.
Ave Caesar!
output.
Ghdu Mxolxv,
Ohw xv phhw qhdu
wkh Wkhdwuh ri Srpshb
dw vxqgrzq.
Dyh Fdhvdu!
With a command line argument of -12
, i.e.: ./caesar -12
input.
Ftq cguow ndaiz raj
vgybe ahqd ftq xmlk pas.
Ftq ruhq najuzs
iulmdpe vgyb cguowxk.
output.
The quick brown fox
jumps over the lazy dog.
The five boxing
wizards jump quickly.
Here are a few tips:
solve rot13 first;
modularize your code using functions;
use input redirection with <
to facilitate the testing of your program
for Haskell programmers:
try next: brutus
Copyright © 2020-2023 Rudy Matela
This text is available under the CC BY-SA 4.0 license.
Originally available on cscx.org/caesar