Explanation The ciphertext is generated from the plaintext by “adding” corresponding characters of the plaintext and the key together. If the plaintext is shorter than the key, only some of the key will be used. Similarly, if the plaintext is shorter than the key, the key will be used multiple times.
For example, to encode the plaintext “HELLO” with the key “CAT”:
Plaintext: HELLO
Key: CATCA
Ciphertext: KFFOP
And to encode the plaintext “DOG” with the key “FIDO”:
Plaintext: DOG
Key: FID
Ciphertext: JXK
To add two letters together, use the following convention: A=1, B=2, …, Z=26. If the sum of two letters is greater than 26, subtract 26 from the sum. For example: A + E = 1 + 5 = 6 = F, and D + X = 4 + 24 = 28 = 2 = B.
Help me guys.
Here is my code:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100],k[50],str1[100];
int i,n;
gets(str);// Input plain text.
gets(str1);//Input key.
for(i=0;str[i]!='\0';i++)
{
n=(str[i]-65+1)+(str1[i]-65+1);//Extracting the numerical position and adding them.
if(n>26) //if numerical value exceeds 26 then subtracting 26 from it and getting the numerical value.
{
n=n-26;
}
str[i]=n+64;//storing the ciphered character.
}
for(i=0;str[i]!='\0';i++)//printing the ciphered characters.
printf("%c",str[i]);
return 0;
}
You can use another loop variable an make the index of the key 0 every time it reaches its length. I have used variable j in this case. Try this code:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100],k[50],str1[100];
int i,n;
gets(str);// Input plain text.
gets(str1);//Input key.
int lenk=strlen(str1),j; //calculate length of key
for(i=0,j=0;str[i]!='\0';i++,j++)
{
if(j==lenk) j=j-lenk; //make j=0
n=(str[i]-65+1)+(str1[j]-65+1); // add str1[j] instead
if(n>26)
{
n=n-26;
}
str[i]=n+64;//storing the ciphered character.
}
for(i=0;str[i]!='\0';i++)
printf("%c",str[i]);
return 0;
}
NOTE THAT THIS WORKS ONLY FOR CAPITAL LETTER, YOU HAVE TO CHANGE YOUR CODE FOR SMALL LETTERS