can someone reformat the code below based on the below assignment? Assignment Tr
ID: 3747605 • Letter: C
Question
can someone reformat the code below based on the below assignment?
Assignment
Transposition Cipher (encrypt.c):
A very simple transposition cipher encrypt(S) can be described by the following rule:
If the length of S is 1 or 2, then encrypt(S) is S.
If S is a string of N characters s1 s2...sN and k=N/2, then
enc(S)=encrypt(sksk-1...s2s1)+encrypt(sNsN-1...sk+1)
where + indicates string cancatenation.
For example, encrypt("OK")="OK" and encrypt("12345678")="34127856".
Write a program to implement this cipher, given an arbitary text string from keyboard, up to 8192 characters. It's better to write a separate encryption function, similar to the following:
Input Format:
an abitary string (with the length up to 8192 characters).
Sample Input:
Test early and often!
Output Format
Line 1: One integer: the toal number of characters in the string.
Line 2: The enciphered string.
Sample Output:
Code
#include<stdio.h>
#include<string.h>
char* encrypt(char *string, size_t length);
void main()
{
char s[8192];char *enc;
printf("enter string: ");
scanf("%s",&s);
enc=encrypt(s,strlen(s));
printf("%s",enc);
}
char* encrypt(char *string, size_t length) {
int n=length;
int k=n/2;k--;
char encstr[length];int i;int c=0;
for(i=k;i>0;i=i-2)
{
encstr[c]=string[i-1];c=c+1;
encstr[c]=string[i];c=c+1;
}
for(i=n-1;i>k+1;i=i-2)
{
encstr[c]=string[i-1];c=c+1;
encstr[c]=string[i];c=c+1;
}
encstr[c]='';
char *enc;
enc=encstr;
return enc;
}
Explanation / Answer
#include<stdio.h>
#include<string.h>
char *encrypt(char *string, size_t length);
void main()
{
char s[8192];
char *enc;
printf("Enter string: ");
scanf("%[^ ]%*c",&s);
enc = encrypt(s,strlen(s));
printf("%s",enc);
}
char *encrypt(char *str, size_t length)
{
int n=length;
int k = n/2;
k--;
char *encstr = (char *)malloc(sizeof(char)*length);
int i;
int c=0;
for(i=k ; i>0 ; i=i-2)
{
encstr[c]=str[i-1];
c=c+1;
encstr[c]=str[i];
c=c+1;
}
if(i == 0){
encstr[c] = str[0];
c = c+1;
}
for(i=n-1;i>k+1;i=i-2)
{
encstr[c]=str[i-1];
c=c+1;
encstr[c]=str[i];
c=c+1;
}
encstr[c]='';
return encstr;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.