Welcome! Today I am going to go through my solution on the Vigenere cipher that is in Problem Set 2 of Harvard’s CS50 course. If you have been following these posts, you will notice that this looks a lot like Caesar’s cipher from last week. That is because we will be starting this exercise by copying our code from the previous solution. So, if there is something in this example that I don’t cover, please refer to my previous post. Now, let’s get started.

The first difference that you will notice between Caesar and Vigenere is that I start by declaring three variables and I set one of them equal to 0. I will come back to these and explain their existence later. Next, with Caesar we were expecting a command line argument that was a non-negative number. In this case, we are expecting a string input from the user as our cipher. So, our string s variable is set equal to the second command line argument, which is our users input. Next, I use a for loop to enumerate through the string to make sure that each character is an alpha. This is important, as we do not want the user to type an any numbers or other characters. If the character is found to not meet this condition, the user will be asked to “Try Again” and the program will return 1 indicating that an error has occurred.

The main difference between Caesar and Vigenere comes in the for loop that encrypts our text. For the isupper and islower portions I have added three lines of code that were not present in Caesar. The first line is where we use modular arithmetic to loop back through our keyword if the text that we are encrypting is longer than the keyword. On the next line we set k equal to the the number that the current character in is in the alphabet. We do this by simply subtracting 97 from the character. So, “a” will move the text by one character, whereas “c” will move the text by three characters. The last line increments the variable l so that each time we pass through the loop we are using the next character in the keyword. And, as in Caesar, we print each character to the screen after the line “ciphertext: “.

And that is all there is to the Vigenere cipher. I am interested on your take on this problem. If you have completed the problem, comment below with a link to your GitHub profile. If you enjoyed this post, please share on your favorite social media platform by clicking one of the buttons below. As always…Happy Programming!

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s