pset2

Pset2 is about cryptography. The first file below, initials.c, is a simple program that prints out the initials of a given name. The rest of the files are cryptography files based on caesar cipher and vigenere cipher.

initials.c

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

int main(void)
{
 string name = GetString();
 printf ("%c", toupper(name[0]));

 for (int i = 0, n = strlen(name); i < n; i++)
 {
 if ( name[i] == ' ' && name[i + 1] != \0)
 {
 printf ("%c", toupper(name[i+1]));
 i++;
 }
 }
 printf ("\n");
}

caesar.c

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

int main(int argc, string argv[])
{
int key;
int ctxt;

if (argc != 2)
{
printf ("please enter a valid key: \n");
return 1;
}

string plntxt = GetString();
key = atoi(argv[1]);

if (key >= 26)
{
key = (key % 26);
}
for (int i = 0, length = strlen(plntxt); i < length; i++) { ctxt = (plntxt[i] + key); if (isupper(plntxt[i]) && (ctxt > 'Z'))
{
ctxt = (ctxt - 26);
}

if (islower(plntxt[i]) && (ctxt > 'z'))
{
ctxt = (ctxt - 26);
}
if (isalpha(plntxt[i]))
{
printf("%c", ctxt);
}
else
{
printf("%c", plntxt[i]);
}
}
printf ("\n");
return 0;
}

vigenere.c

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

int main (int argc, string argv[])
{

int shift;
int keyword;

if (argc != 2)
{
printf("please enter an alphabetical keyword\n");
return 1;
}

string key = argv[1];

for (int n = 0, keylength = strlen(argv[1]); n < keylength; n++) { if ((key[n] >= '0') && (key[n] <= '9'))
{
printf("please only enter letters/words.\n");
return 1;
}
}

string plntxt = GetString();

for(int i = 0, j = 0, length = strlen(plntxt); i < length; i++, j++) { if (j >= strlen(key))
{
j = 0;
}
keyword = key[j];

if (!isalpha(plntxt[i]))
{
j = (j - 1);
}

if ((keyword >= 'A') && (keyword <= 'Z')) { keyword = (keyword - 'A'); } if ((keyword >= 'a') && (keyword <= 'z')) { keyword = (keyword - 'a'); } shift = (plntxt[i] + keyword); if (isupper(plntxt[i]) && (shift > 'Z'))
{
shift = (shift - 26);
}

if (islower(plntxt[i]) && (shift > 'z'))
{
shift = (shift - 26);
}

if (isalpha(plntxt[i]))
{
printf("%c", shift);
}

else
{
printf("%c", plntxt[i]);
}

}
printf("\n");
return 0;
}

Leave a comment