0
votes

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:

  1. Get key from command line argument.
  2. turn key (k) into integer.
  3. prompt user for plain text (pi)
  4. for each plain text character, preserve the case (using isalpha, isupper and islower functions in C.
  5. 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.
  6. 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]);
     }
1
Is there a question in here somewhere? - Colin
just edited my question. I am struggling to shift the letters as I have mentioned in my pseudocode. - Aakash
What is c? It's not declared in this scope. You have the right idea, but when you % 26 you 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. - Colin
isalpha('p') will always return true, since p is a letter., perhaps you meant isalpha(p[i]). - bartonjs
Thanks! I am trying to print the ASCII character, should I add "a" or "A" to print the alphabet? - Aakash

1 Answers

0
votes

Actually ,the code you have written will simply return the value of plain text you have entered logic for this question is c[ i ]=( p[ i ] +k)%26 you have to make apply this formula differently for both upper and lower case I can give you a snippet of the code ,this will help you in solving your problem

int l = (p[ i ] -65+k)%26 printf("%c",l+65);

Here, k is the key In this I have used the ASCII values of the letters as the ASCII values is integer ,I have used a integer to store the value and apply the operation given . I have used 65 because ASCII value of upper case 'A' is 65. As we have to print the character we have used %c to print the character . This was for the upper case ,you can do similar with the lowercase If this answer was helpful , please click the arrow beside this Thank you :)