For example, if entered key is 2 then characters will be replaced by 2 characters down to it. Like, A will be replaced by C, B by D and so on. Below image show shifting of characters by key value 2.
/*Caesar Cipher Program in C*/
#include
#include
#include
int main(void){
int key;
char plainText[101];
int i=0;
int cypherValue;
char cypher;
clrscr();
printf("Please enter the plain text you want to encrypt: ");
fgets(plainText, sizeof(plainText), stdin);
printf("\nPlease enter key: ");
scanf("%d",&key);
printf("\nThe ciphered text is : ");
while( plainText[i] != '\0' && strlen(plainText)-1 > i){
cypherValue = ((int)plainText[i] -97 + key) % 26 + 97;
cypher = (char)(cypherValue);
printf("%c", cypher);
i++;
}
printf("\n\n");
system("pause");
}
Output:#include
#include
int main(void){
int key;
char plainText[101];
int i=0;
int cypherValue;
char cypher;
clrscr();
printf("Please enter the plain text you want to encrypt: ");
fgets(plainText, sizeof(plainText), stdin);
printf("\nPlease enter key: ");
scanf("%d",&key);
printf("\nThe ciphered text is : ");
while( plainText[i] != '\0' && strlen(plainText)-1 > i){
cypherValue = ((int)plainText[i] -97 + key) % 26 + 97;
cypher = (char)(cypherValue);
printf("%c", cypher);
i++;
}
printf("\n\n");
system("pause");
}
Please enter the plain text you want to encrypt: HelloWorld
The ciphered text is: JgnnqYqtnf
The ciphered text is: JgnnqYqtnf