Task: Caesar’s algorithm (cipher (c)) encrypts messages by "rotating" each letter by key (k) positions.
To implement: ci = (pi+k)mod26 where ci is cipher, pi is plaintext and k is key.
My Pseudocode:
- Get key from command line argument.
- turn key (k) into integer.
- prompt user for plain text (pi)
- for each plain text character, preserve the case (using isalpha, isupper and islower functions in C.
- Finally shift plaintext character by key for example - "Go Home!" --- "Hp Ipnf!" (if key k =1, and preserving the upper/lower case of letters, ! remains as !). ** I am Struggling with this.
- Print ciphertext.
int main (int argc, string argv[]) //get key from command line argument
{
if (argc != 2 || atoi(argv[1]) < 0)
{
printf ("print valid key");
return 1;
}
int k = atoi(argv[1]);
string p = get_string(); //prompt for plaintext
for (int i=0, n = strlen(p); i < n; i++)
{ if (isalpha('p'))
{
if (isupper('p'))
{
printf ("%c", p[i]);
}
if (islower('p'))
{
printf ("%c", p[i]);
}
}
}
c[i]=(p[i]+k)%26;
printf ("%c", c[i]);
}
c? It's not declared in this scope. You have the right idea, but when you% 26you end up with a number between 0 and 25, these are mostly unprintable ASCII characters, you need to add'a'or'A'back to it to get them within the alphabet. - Colinisalpha('p')will always return true, since p is a letter., perhaps you meantisalpha(p[i]). - bartonjs