Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid

sojohnnysaid/caesar.c

Last active Feb 22, 2018
Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>
#define UPPER_ALPHA_INDEX 65
#define LOWER_ALPHA_INDEX 97
#define ALPHABET_MAX 26
char encipher(char index, int cipher_key);
int main(int argc, string argv[])
{
// Get the key from the user
int cipher_key;
// Guard against the user not entering the correct number of command line arguments
if(argc != 2 || atoi(argv[1]) <= 0)
{
printf("Error: Incorrect number of arguments passed or value not a positive number!\n");
return 1;
}
else
{
cipher_key = atoi(argv[1]);
}
// Get the plain text they want to encode
string cipher_text = "";
do
{
printf("\nNOTE: Only uppercase and lowercase letters will be encoded\n");
cipher_text = get_string("Please enter the text to encode to continue: ");
}
while(strlen(cipher_text) == 0);
// Encipher
printf("ciphertext: ");
for (int i = 0; i < strlen(cipher_text); i++)
printf("%c", encipher(cipher_text[i], cipher_key));
printf("\n");
}
// The way to encipher is by understanding the ascii indicies for each letter.
// Because lowercase letters and uppercase letters have arbitrary indicies
// we must first adjust the indicies so 'a' and 'A' start at index 0
// This is done by subtracting either UPPER_ALPHA_INDEX or LOWER_ALPHA_INDEX
// once the index is in the correct mapping we can add or subtract the cipher key
// and use the modulo operator to get the new index
// finally we re-adjust back up to the ascii index
// by adding back UPPER_ALPHA_INDEX or LOWER_ALPHA_INDEX
// Anything that isn't a character is returned back to the caller
char encipher(char index, int cipher_key)
{
if (isupper(index))
return ((index - UPPER_ALPHA_INDEX) + cipher_key) % ALPHABET_MAX + UPPER_ALPHA_INDEX;
else if (islower(index) )
return ((index - LOWER_ALPHA_INDEX) + cipher_key) % ALPHABET_MAX + LOWER_ALPHA_INDEX;
else
return index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.