I’m trying to make a simple encryption program with C. My aim is to translate abc (it can be any word) to 123. Then multiply 2 and get 246 then again translate to text, then write on screen bdf. Here is my algorithm which is not working correctly. I entered abc and I got cbc. Can you help me?
int main()
{
int z,o,c,l,i,j,k,*D;
char word[10];
char alfabe[24]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','y','z','\0'};
printf("enter word");
scanf("%s",word);
c=strlen(word);
printf("has %d letters ", c);
D = (int *) malloc( sizeof(int)*c );
for(i=0;i<c;i++) {
for(j=0;j<26;j++) {
if(word[i]==alfabe[j]) {
D[i]=2*(j+1);
break;
}
}
}
printf("\nlast form before translation ");
for(l=0;l<c;l++) {
printf("%d",D[l]); /*it s just for control */
}
for(z=0;z<c;z++){
printf("%c",alfabe[o]);
o=D[z];
word[z]=alfabe[o] ; break; }
printf("\nnew form of word: ");
for(k=0;k<c;k++) {
printf("%c",word[k]);
}
scanf("%d");
}
OK, first of all
'\0'marks the end of an inputed string, you don’t need to encrypth this particular character, my suggestion is to place it first in thealfabetso you would get:This will save you the trouble of substracting 1, so you will have:
In the part where you encode the input. And when you generate the output word:
No need for
oand especially nobreak;in the loop.A more efficient way would be to create a function that handles the encryption of the string passed:
I’ve added
'x'in thealfabet– that is the reason why now there are 25 elements. I’m sure there is one character of the English alphabet missing, but it’s 3 AM here and English isn’t my primary language. Also, this solution is working on the assumption that thealfabetyou provided are the only characters that are supposed to exist in the input and output.