Created
December 6, 2019 10:14
-
-
Save AnimeshRy/bd6eec8c2404ba3161ca10f672b76b09 to your computer and use it in GitHub Desktop.
Easy Caesar CS50 version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <cs50.h> | |
int main(int argc, string args[]) | |
{ | |
if (argc != 2) | |
{ | |
printf("Usage: ./caesar k"); | |
return 1; | |
} | |
int k = atoi(args[1]) % 26; // if k is > 26, store the division remainder instead | |
string plaintext = get_string("plaintext: "); | |
printf("ciphertext: "); | |
for (int i = 0; i < strlen(plaintext); i++) | |
{ | |
if (!isalpha(plaintext[i])) | |
{ | |
printf("%c", plaintext[i]); | |
continue; | |
} | |
int ascii_set = isupper(plaintext[i]) ? 65 : 97; | |
int pt = plaintext[i] - ascii_set; | |
int ct = (pt + k) % 26; | |
printf("%c", ct + ascii_set ); | |
} | |
printf("\n"); | |
return 0; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. This may look a little complex at first but it was easy to understand after a while. | |
2. The older version I made for caesar was very easy and it should be that way, it had if else statements combined with the islower and isupper but this one is a little more complex but hella clean. | |
3. The "?" in line 28 is the ternary operator which basically makes the if else statement short and concise. It's better if you avoid as it makes things a little difficult to understand. | |
4. The "65" and "97" are ranges to convert meaning if I change the "isupper" to "islower", I'd have to change positions of 97 to 65 as the Upper limit start at 65 and lower at 97 in ascii. | |
5. I made a seperation function to subtract the ascii offset to reset the count to 0-1-2-3-.. to make the alphabetic postions in their natural order. You could do ((Ci = pi - 97/26 + k)%26 + 97/26) but use them in different if else statements. | |
6. The modulo math is simple, think of it with respect to a clock - While viewing time of the clock, we use mod12 so similary we use mod 26 with caesar as 26 is the total letters count and to reset the count whenever the key is larger than 26 we mod it and start over. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice