Encrypt Letters with a Caesar Cipher Project
Alright, are you ready to make a project that does what you just did by hand?
Before getting started, think about this set of steps as a conversion between by-hand to pseudo code for programming.
- Store the key in a variable
- Store the plaintext letter you are starting within a variable
- Create an alphabet
- Find the index of that plaintext letter in the alphabet
- Add the key to the index
- Find and store the ciphertext letter at the new index
Now let’s go!
Find a Character
A project that does the Caesar cipher has to start by finding a character in an alphabet. In this example, you will make a project that creates an alphabet string and finds the index of a certain character. In other words, it will tell you that A has an index of 0, B has an index of 1, and so on, up through Z, which has an index of 25.
Example project: find_letter_in_alphabet
- Enter find_letter_in_alphabet.
- Flash it into the micro:bit.
When the project runs, the terminal should print index = 12 since that is the index of M in the string alpha.
- Make sure your keyboard is set to CAPS LOCK.
- Open the terminal and verify that it displays:
letter = M, index = 12 - Change set letter to (“M”) to set letter to (“D”).
- Flash the modified project.
- Verify that the terminal displays:
letter = D, index = 3 - Repeat this process for “A”, “B”, “Y”, and “Z”.
How find_letter_in_alphabet Works
Every cipher begins with an alphabet, so the project starts by creating a string named alpha, which contains all the uppercase letters in the alphabet.
The () find index of () method is something available to each string in Makecode. () find index of () searches the string for whatever text is passed to it from inside the second parentheses, and it returns the index where the text is first located. Remember that the index numbers in a string start at zero. So, the first character A has an index of 0, B has an index of 1, and so on, through Z with an index of 25. In this counting system, M has an index of 12 in the alpha string. So, set letter to (“M”) followed by (alpha) find index of (letter) returns 12.
“…and now, for something completely different!”
You might have already experimented with the () find index of () method in Try This: Find the Substring. It had examples of finding the starting index values of words like “Arthur” and “run”, and even used the index to decide what to do next. In this encryption example, the alpha string’s () find index of () method is instead used to locate a single letter within a string.