In: Computer Science
In C++, write a program to implement the Caesar Cipher for both encryption and decryption.
The program should be able to handle different keys by deciding the key at run time.
Thank you :)
#include<iostream>
using namespace std;
//function to encrypt
void encrypt(char message[],int key)
{
int i;
char ch;
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;
}
}
}
//method to decrypt
void decrypt(char message[],int key)
{
int i;
char ch;
for(i = 0; message[i] != '\0';
++i){
ch = message[i];
if(ch >= 'a' && ch <=
'z'){
ch = ch -
key;
if(ch <
'a'){
ch = ch + 'z' - 'a' + 1;
}
message[i] =
ch;
}
else if(ch >= 'A' && ch
<= 'Z'){
ch = ch -
key;
if(ch >
'a'){
ch = ch + 'Z' - 'A' + 1;
}
message[i] =
ch;
}
}
}
int main()
{
char message[100], ch;
int i, key;
cout << "Enter a message to encrypt: ";
cin.getline(message, 100);
cout << "Enter key: ";
cin >> key;
encrypt(message,key);//calling method to encrypt
cout << "Encrypted message: " <<
message<<endl;
decrypt(message,key);//calling method to decrypt
cout << "Decrypted message: " <<
message<<endl;
return 0;
}
output:
Enter a message to encrypt: Hello
Enter key: 3
Encrypted message: Khoor
Decrypted message: Hello
Process exited normally.
Press any key to continue . . .