1

I understand the necessity of using the modulus operator to compensate for plaintext characters that would surpass Z or z respectively, but I cannot seem to wrap my head around its particular syntax. Could someone briefly explain its usage without providing the exact syntax? See my work in progress below..

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

//declare main with command line argument functionality
int main(int argc, string argv[])
{
    //return error message if uncorrect # of arguments
    if (argc != 2)
    {
        printf("Please provide one and only one key.\n");
        return 1;
    }
    else
    {
        //get key from command line arugment
        //turn key into integer
        int k = atoi(argv[1]);

        //prompt for plaintext
        printf("plaintext: ");
        string p = get_string();

        //for each character in plaintext string
        for (int i = 0, n = strlen(p); i < n; i++)
        {
            //create new variable for ith character in plaintext
            int a = p[i];

            //check if alphabetic and preserve case
            if (isalpha(a) && isupper(a))
            {
                //shift plaintext character by key
                int c = (a + k);

                //print ciphertext
                printf("%c", c);
            }
            //check if alphabetic and preserve case
            else if (isalpha(a) && islower(a))
            {
                //shift plaintext character by key
                int c = (a + k);

                //print ciphertext
                printf("%c", c);
            }
        }
        printf("\n");
    return 0;
    }
}

1 Answer 1

1

Modulo is like a 12-hour clock. If it's 8:00 and you add 7 hours, you have to wrap around so you don't end up with 15:00, but with 3:00.

(8+7)%12 = 3

(mathematically, it's the remainder of long division, so 15 divided by 12 is 1 with 3 left over.)

In the same way, if you have brought your chars down to the range of 0-25 (as explained in the walkthrough), then the caesar formula:

(plaintext+key)%26

works the same way, such that if your plaintext is 'y' (24) then 'y' + 5 = 'd'

(24+5)%26 = 3 (= 'd')

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .