Skip to content

Instantly share code, notes, and snippets.

@CraigRodrigues
Last active June 2, 2016 20:03
Show Gist options
  • Save CraigRodrigues/6e3724fbe3bd5fed9d05d2cafcedbc5c to your computer and use it in GitHub Desktop.
Save CraigRodrigues/6e3724fbe3bd5fed9d05d2cafcedbc5c to your computer and use it in GitHub Desktop.
My solution to CS50 pset2 - "Hail, Caesar!" (using function)
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
/**
* Caesar.c
* A program that encrypts messages using Caesar’s cipher. Your program must
* accept a single command-line argument: a non-negative integer. Let’s call it
* k for the sake of discussion. If your program is executed without any
* command-line arguments or with more than one command-line argument, your
* program should yell at the user and return a value of 1.
*
* */
// function that encrypts a character based on the key submitted
int encryptCode(char code, int key)
{
if islower(code)
{
code = ((((code + key) - 97) % 26) + 97);
return code;
}
else if isupper(code)
{
code = ((((code + key) - 65) % 26) + 65);
return code;
}
//if neither then just return whatever it is
else
return code;
}
int main(int argc, string argv[])
{
// check for 2 arguments only
if (argc != 2)
{
printf("Nope\n");
return 1;
}
// once I check for correct argv put key into an int k
int k = atoi(argv[1]);
// check if the integer is non-negative
if (k < 0)
{
printf("Nope\n");
return 1;
}
else
{
// prompt user for a code to encrypt
string code = GetString();
for (int i = 0, n = strlen(code); i < n; i++)
{
printf("%c", encryptCode(code[i], k););
}
printf("\n");
return 0;
}
}
@CraigRodrigues
Copy link
Author

Line 63 can just be: printf("%c", encryptCode(code[i], k));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment