Skip to content

Instantly share code, notes, and snippets.

@AnimeshRy
Last active December 6, 2019 10:33
Show Gist options
  • Save AnimeshRy/3cf26209006a91fc092a59af85deaa72 to your computer and use it in GitHub Desktop.
Save AnimeshRy/3cf26209006a91fc092a59af85deaa72 to your computer and use it in GitHub Desktop.
CS50 Vigenere 2019
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
// Check if correct # of arguments given
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
else
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Usage: ./vigenere keyword");
return 1;
}
}
}
// Store key as string and get length
string k = argv[1];
int kLen = strlen(k);
// Get text to encode
string p = get_string("PLaintext: ");
printf("Ciphertext: ");
// Loop through text
for (int i = 0, j = 0, n = strlen(p); i < n; i++)
{
// Get key for this letter
int letterKey = tolower(k[j % kLen]) - 'a';
// Keep case of letter
if (isupper(p[i]))
{
// Get modulo number and add to appropriate case
printf("%c", 'A' + (p[i] - 'A' + letterKey) % 26);
// Only increment j when used
j++;
}
else if (islower(p[i]))
{
printf("%c", 'a' + (p[i] - 'a' + letterKey) % 26);
j++;
}
else
{
// return unchanged
printf("%c", p[i]);
}
}
printf("\n");
return 0;
}
@AnimeshRy
Copy link
Author

Notes -

  1. This is a little more complex then caesar and it took me around 6 hours to figure out how to warp around the letters which was the main part for vigenere.
  2. First is the simple part, which is similar to caesar as we use the same argc and for the character being a alphabet we used the for loop to iterate over each letter of the key and to check we used isalpha() in the ctype.h library.
  3. On line 31, we got to know the length of the key by storing and then storing it in klen.
  4. In line we used tolower() to change the key to all lower and then subtract the ascii of 'a' to get a natural alphabet, we could have used toupper() function too and then subtract the ascii of 'A'.
  5. The math is similar to caesar, in caesar we used %26 to reset the count for a larger number and offcourse the alphabet count is 26 but here we used j%klen to reset the value if the key is smaller than the plaintext. Remember we are iterating over each character key so we used the second variable for it and we have to increment it inside the loop.
  6. Then there is the simple if else to conserve the letter case and spaces.

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