<mosaic.cnfolio.com>
PROGRAM
  1. //Coursework 2 , cipher key
  2. #include<stdio.h>
  3. #include<string.h>
  4. #include<stdlib.h>
  5. /* Coursework 2 , cipher key
  6.    set cipher key to be "hg"
  7.    set plain text to be " hello world"
  8.    set letter 'h' to be N , which N==1
  9.    replace h with g , set g to be N+1
  10.    substitute 'g' into 'h' of " hello world"
  11.    plain text becomes " gello world "
  12.    first program complete */
  13.  
  14. /* set cipher key to be "hgw"
  15.    set plain text to be " hello world"
  16.    set letter 'h' to be N , wich N==1
  17.    substitute 'h' with 'g' and get " gello world "
  18.    'g' becomes N+1
  19.    substitute 'g' with 'w' , get " gello world "
  20.    'w' becomes N+2
  21.    subsitute 'w' with 'h' , get " gello horld "
  22.    second program complete */
  23.    
  24.  
  25. const int MAXSIZE = 100;
  26.  
  27. char *encrypt(char *essay) {
  28.     int i,j,n,u,v,m,len = strlen(essay);
  29.     char *result;
  30.     m = n = (int)sqrt(len);
  31.     if(m * m < len) ++n;
  32.     result = (char *)malloc(m * n * sizeof(char) + 1);
  33.     for(i = 0; i < m; ++i) {
  34.     for(j = 0; j < n; ++j) {
  35.     u = n * i + j;
  36.     v = m * j + i;
  37.     if(u < len) result[v] = essay[u];
  38.     else result[v] = ' ';
  39.     }
  40.     }
  41.     result[m * n] = 0;
  42.     return result;
  43.     }
  44.  
  45. int main() {
  46.     char s[MAXSIZE],*u;
  47.     printf("enter plain text:\n");
  48.     fgets(s,MAXSIZE,stdin);
  49.     s[strlen(s) - 1] = 0;
  50.     u = encrypt(s);
  51.     printf("display cipher text:\n%s\n",u);
  52.     free(u);
  53.     return 0;
  54.     }