CS50 Caesar Solution

By Suraj Chaudhary

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.

Also Read

  1. CS50: How To Study At Harvard For FREE (and get a free certificate)
  2. How to use Windows 11 on Mac for Free
  3. How To Get A Domain Name For FREE
  4. How To Use Microsoft Office Apps For FREE Legally (Mac & PC)

Suraj Chaudhary is a writer, developer, founder, and a constant learner. He shares lessons and resources for living a fuller life every week. On this blog, he shares helpful guides and helpful articles that help his 70,000+ monthly readers find answers, solve problems, and meet their curious needs.

Leave a Comment

Slide to prove you're not a bot/spammer *