Are you looking for the solution of Harvard’s CS50 PSet 2? Do you want the CS50 Caesar Solution of week 2?
If so you’re in the right place.
In this article, I’m going to share with you exactly how to solve the CS50 Caesar problem and will also share the CS50 Caesar solution with you.
Here’s how to solve the CS50 Caesar problem.
The first thing to do is to understand what we are trying to build. You can read the instructions from CS50’s website.
Caesar is used to “encrypt” (i.e., conceal in a reversible way) confidential messages by shifting each letter therein by some number of places. For instance, he might write A as B, B as C, C as D, …, and, wrapping around alphabetically, Z as A. And so, to say HELLO to someone, Caesar might write IFMMP instead.
Upon receiving such messages from Caesar, recipients would have to “decrypt” them by shifting letters in the opposite direction by the same number of places.
Here’s my entire code for the CS50 Caesar Solution:
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
for (int l = 0; l < strlen(argv[1]); l++)
{
if (isalpha(argv[1][l]))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
int key = atoi(argv[1]);
string text = get_string("plaintext: ");
for (int i = 0; i < strlen(text); i++)
{
if (isalpha(text[i]))
{
if (isupper(text[i]))
{
text[i] = (((text[i] - 65) + key) % 26) + 65;
}
if (islower(text[i]))
{
text[i] = (((text[i] - 97) + key) % 26) + 97;
}
}
}
printf("ciphertext: %s\n", text);
}
If you have any confusion or problem, feel free to drop a comment down below. In the meantime, you can read these articles.