cs50 pset2: Caesar

Caesar is the less comfortable task of problem set 2 for the CS50: Introduction to Computer Science course and let me tell you, looking back from here, Mario was so much easier. For this task, we had to include the following extra files for the first time:

#include <ctype.h> 
#include <stdlib.h> 
#include <string.h>

The main point of the task was to convert plaintext to ciphertext through encryption, using a key. The concept came from Julius Caesar, who used secret messages to communicate with his army.


Having to use the command line argument:

int main(int argc, string argv[])

was honestly a little confusing at first and I watched quite a few videos on it on YouTube to help me figure out what the piece of code actually meant. Here's a video by Paul Programming that helped me out, in case you'd like to understand command line arguments better: https://www.youtube.com/watch – as well as this, remember to check out all the shorts videos that are already provided in the course since those can be really helpful too!


After this, we needed to check whether only two arguments were being inputted and if not, we had to return an error value of 1:

(argc != 2)
{         
    printf("Error: enter two arguments only\n");
    return 1;
}

As well as that, we had to make sure that the key that was being inputted was an integer/digit and it's also really important to make sure that the key is positive and not a value < 0.


From here, the task got a lot trickier. After asking for plaintext using the get_string command, we needed to find the length of that plaintext using strlen. Then we needed to change each character of the plaintext to change it into the ciphertext. This is how I did that:

printf("ciphertext: ");
for (int i = 0; i < length; i++)            
{
    //lower letters
    if (islower(plaintext[i]))
    {
        printf("%c", (((plaintext[i]+key)- 97)% 26)+ 97);                
    }
    //capital letters
    else if (isupper(plaintext[i]))        
    {
        printf("%c", (((plaintext[i]+key)- 65)% 26)+ 65);                
    }
    //prints out ciphertext
    else            
    {
        printf("%c", plaintext[i]);
    }            
}

This bit was really difficult and it took me around 1-2 days to finally figure it out. I was also trying to keep the code as concise as possible and I think I managed to do that. Let me know if you understand the code or if yours was any different. I hope you found this post helpful!


If you'd like to know more about CS50's Introduction to Computer Science course, read this post here.

47 views

Recent Posts

See All
  • White Twitter Icon
  • White Instagram Icon
  • Github
  • letterboxd
  • White LinkedIn Icon
  • YouTube - JustJan

© 2020 by Janhavi Purkar