I found this Caesar cipher encryption code on the web and I'm trying to understand how it works
#include<stdio.h>
int main()
{
char message[100], ch;
int i, key;
printf("Enter a message to encrypt: ");
gets(message);
printf("Enter key: ");
scanf("%d", &key);
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch + key;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
printf("Encrypted message: %s", message);
return 0;
}
Meaning of if(ch >= 'a' && ch <= 'z')
Like does c include the alphabet as an array or something or how does it know that the letter is b or others ?
Adding an int to a char in ch = ch + key;
this math thing ch = ch - 'Z' + 'A' - 1;
And thanks very very much
The codes adds a certain value (key
) to each inputed character and "rotates" the character in the range a-z
if small caps and A-Z
if big caps.
In C each single character has an implicit ascii/int
value and the compare operator is used to decide if the inputted character is in the set of characters a-z
(which are aligned after each other) or if it is in the set of A-Z
which also follow behind each other.
The rest of the code deals with the wraparound if the inputted character plus the key
"overshoots" f.e. z
or Z
and loops it around by substracting the value of 'z'
and adding the value of 'a' -1
so that the resulting char is again one in the selected range of a-z
or A-Z