Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function encrypt that takes two strings \"s1\" and \"s2\" and an integer

ID: 3816153 • Letter: W

Question

Write a function encrypt that takes two strings "s1" and "s2" and an integer "shift" as parameters. Your function encrypts s1 and stores it in s2. The encryption is done by shifting each character "shift" number of places For example if shift is 4, then every A in the s1 becomes E in s2, and B becomes F and so on. Z becomes the character 'Z' 4 which is^according to the ASCII table. Write another similar function decrypt (that takes two strings "s1" and "s2" and an integer "shift" as parameters) and decrypts s1 by shifting its characters back "shift" places and storing it in s2. Both functions should take s1 and s2 as char parameter (pointer to char) Write a program encryption.c that reads a sentence from the user and encrypts it then decrypts it. Your program should ask the user to enter a sentence and an integer denoting the shift number. Your program should then encrypt the string and output the encrypted result. Then it decrypts the result and outputs it to the standard output.

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encrypt(char *str1, char *str2, int shift)
{
int length = strlen(str1);
int i = 0;
  
// char in c act like integer so adding shift will decrypt it
// also not char range from -128 to 127 and hence they roll around if value goes
// above or below
for(i = 0; i < length; i++)
{
str2[i] = str1[i] + shift;
}
}

void decrypt(char *str1, char *str2, int shift)
{
int length = strlen(str1);
int i = 0;
  
// char in c act like integer so subtracting shift will decrypt it
// also not char range from -128 to 127 and hence they roll around if value goes
// above or below
for(i = 0; i < length; i++)
{
str2[i] = str1[i] - shift;
}
}

int main()
{
char str1[1000];
char str2[1000];
int shift;
printf("Enter string to encrypt: ");
fgets (str1, 100, stdin);
  
printf("Enter shift: ");
scanf("%d", &shift);
  
encrypt(str1, str2, shift);
printf("Encrypted string: %s ", str2);
  
char decrypted[1000];
decrypt(str2, decrypted, shift);
printf("Decrypted string: %s ", decrypted);

return 0;
}

Sample execution:

Enter string to encrypt: hell abcd ef z
Enter shift: 3
Encrypted string: khoo#defg#hi#}
Decrypted string: hell abcd ef z

Please rate positively if this answered your question.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote