Pages

This blog is under construction

Friday, January 8, 2021

C Program to encrypt a string

 A simple encryption system uses a shifting process to hide a message. The value of the shift can be in the range 1 to 26. For example a shift of 20 means that A = U, B = V, C = W, . . .Y = S, Z = T. So, the shift wraps around after Z. Coding happens as follows: First an extra space is added to the end of the string. Spaces within the original text are replaced with QQ before the text is encrypted. Double Q (QQ) was selected because no English word ends in Q or contains QQ. Additionally the coded message is printed in blocks of six characters separated by spaces. The last block might not contain six characters. Write a program that takes the coded text (assume less than 100 characters), the shift value and prints the decoded original message. Your program must reject any non-valid value for shift and display an error message "INVALID SHIFT VALUE". Assume all characters are upper case. 

Here are some sample inputs and outputs:

INPUT: CODED TEXT: "UHINBY LKKQCH HYLKK", SHIFT: 20

OUTPUT DECODED TEXT: "ANOTHER WINNER"

INPUT: CODED TEXT: "DKSMMW NAMMUK QMM", SHIFT: 29

OUTPUT: INVALID SHIFT VALUE.

Solution: 

#include <stdio.h>

#include <ctype.h>

#include <stdlib.h>

/*Assumes words do not end in Q and QQ is not part of any word. */

int main(void) {

  char s[100];

  int len=0, shift;

  char c;

  printf("Give the coded string (<=100 chars) then ENTER = ");

  c=toupper(getchar());

  while (!iscntrl(c) && c!=EOF && len<101) {

    if (c==' ');//skip space. This is the best time to remove it.

    else {

      if (c<'A' || c>'Z') {printf("Invalid char in input\n"); exit(0);}

      s[len++]=c;

    }

    c=toupper(getchar());

  }

  printf("Give the shift (1 to 26) then ENTER = ");

  scanf("%d",&shift);

  if (shift<1 || shift>26){printf("INVALID SHIFT VALUE\n"); exit(0);}

  //First decode using shift

  for(int i=0; i<len; i++){

    int ci=(int)s[i]-((int)'A'+shift);//ASCII of 'A' is the base

    s[i]=(ci<0)?(26+ci+(int)'A'):(char)(ci+(int)'A');

  }

  //Replace QQ by blank

  int i=0;

  while (i<len) {

    if (s[i]=='Q' && s[i+1]=='Q') {putchar(' '); i+=2;}

    else putchar(s[i++]);

  }

  printf("\n");

  return 0;

}

Output:

Give the coded string (<=100 chars) then ENTER = UHINBY LKKQCH HYLKK

Give the shift (1 to 26) then ENTER = 20

ANOTHER WINNER


Press any key to continue . . .

No comments:

Post a Comment