In: Computer Science
what does this code do?
int encrypt(int character, int shift) {
if(character >= 'a' && character <= 'z') {
return 'a' + (((character-'a'+shift) % 26) + 26) % 26 ;
} else if (character >= 'A' && character <= 'Z')
{
return 'A' + (((character-'A'+shift) % 26) +26) % 26;
} else {
return character;
}
}
int main(int argc, char *argv[]) {
int ch;
int key = 3;
if(argc == 2) {
key = atoi(argv[1]);
}
while((ch = getchar()) != EOF) {
printf("%c", encrypt(ch, key));
}
return 0;
}
how does this work as I am confused about the % used.
Please find the following explanation on given program.
Explanation:
1. This program encrypts the character by using the given key which shifts character based it. If it goes beyond 'z' then it wraps around and starts from 'a'.
2. Here "%" is a modulo operator which returns the reminder of a division.
3. In api we have a hard coded value which is 26 which represents that there are 26 alphabets.
4. Following statement receives our input character, say 'b' and shifts based on given key value,
return 'a' + (((character-'a'+shift) % 26) + 26) % 26 ;
='a' + ((('b' - 'a' + 3) % 26) + 26) %26
='a' + (((1+3)% 26) + 26 ) % 26
= 'a' + (4 + 26) % 26
='a' + 30 % 26
=61 + 4
= 'a' ascii value is 61 so (61+4) retruns 65 which is character 'e'
Sample Program:
#include <stdio.h>
#include <stdlib.h>
int encrypt(int character, int shift) {
if(character >= 'a' && character <= 'z') {
//return 'a' + (((character-'a'+shift) % 26) + 26) % 26 ;
return 'a' + (((character-'a'+shift) % 26) ); // we can
also use this statement to shift the character.
} else if (character >= 'A' && character <= 'Z')
{
return 'A' + (((character-'A'+shift) % 26) +26) % 26;
} else {
return character;
}
}
int main(int argc, char *argv[]) {
int ch;
int key = 3;
if(argc == 2) {
key = atoi(argv[1]);
}
while((ch = getchar()) != EOF) {
printf("%c", encrypt(ch, key));
}
return 0;
}