Example Cipher Program in C

How to write a C  Program Cipher in C Programming Language ?


Solution:
  1.  
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <stddef.h>
  5. #include <string.h>
  6.  
  7. #define MAX 256
  8.  
  9. void cipherize(char cipher[], unsigned int rotation) {
  10.     char c;
  11.     int ci;
  12.     ptrdiff_t ai;
  13.     const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
  14.    
  15.     for (ci = 0; ci < MAX; ci++) {
  16.         if (== '\0') break;
  17.         c = tolower(cipher[ci]);
  18.         if (!isalpha(c)) continue;
  19.         ai = strchr(alphabet, c) - alphabet;
  20.         ai += rotation;
  21.         if (ai >= 26) ai %= 26;
  22.         cipher[ci] = alphabet[ai];
  23.     }
  24. }
  25.  
  26.  
  27. int yesorno(const char *prompt) {
  28.     char answer;
  29.     do {
  30.         printf("%s (y/n): ", prompt);
  31.         scanf(" %c", &answer);
  32.         answer = tolower(answer);
  33.         if (answer != 'y' && answer != 'n')
  34.             puts("y or n.");
  35.     } while (answer != 'y' && answer != 'n');
  36.     return answer == 'y';
  37. }
  38.  
  39.  
  40. int main(void) {
  41.     char original[MAX];
  42.     char cipher[MAX];
  43.     unsigned int rotation;
  44.  
  45.     /* get user input, i'm not responsible if user does it wrong */
  46. getcipher:
  47.     printf("enter a cipher to attempt (max %u chars, hit enter to stop):\n", MAX - 1);
  48.     fgets(original, MAX, stdin);
  49.  
  50. getrotation:
  51.     fputs("enter the rotation (1-25): ",stdout);
  52.     scanf("%u",&rotation);
  53.     if (rotation > 25) {
  54.         rotation %= 25;
  55.         printf("i said 1-25. i'm going with %u.\n", rotation);
  56.     }
  57.     if (rotation < 1) {
  58.         puts("nothing to do!");
  59.         return 0;
  60.     }
  61.    
  62.     /* now the fun part */
  63.     strcpy(cipher, original);
  64.     cipherize(cipher, rotation);
  65.  
  66.     /* give output, prompt user */
  67.     puts("translated to:");
  68.     puts(cipher);
  69.     if (yesorno("try another rotation?")) goto getrotation;
  70.     if (yesorno("enter another cipher?")) goto getcipher;
  71.  
  72.     /* and we are done */
  73.     puts("exiting...");
  74.     return 0;
  75. }


Learn More :