In: Computer Science
use C++
Cryptography is the study of hiding information or encrypting information. Cryptographers often use things called ciphers to encrypt messages. A cyclic cipher is a common, but relatively insecure method of encrypting a message. It is achieved by replacing every letter in the word or message with another letter in the alphabet a certain number of positions away. For example, if the message to be encrypted (the plaintext) was IBM and the cipher key was -1, the resulting message (the ciphertext) would be HAL. 'I' was replaced by the letter one position to the left of it in the alphabet: 'H', etc.
If the letter happens to be 'Y' and the key is 3, the cipher "wraps around" to the beginning of the alphabet and the encrypted letter would be 'B'.
Write a program to "encrypt" one character using a cyclic cipher. You may assume that the character is an alphabetic letter, but it may be given in lowercase or uppercase. The key to the encoding will be the number of characters to move "up" in the alphabet (toward Z); negative numbers move "down" in the alphabet (toward A). You may assume that the key will be greater than -26 and less than 26 (so we will never cycle the whole way through the alphabet). Output the encrypted character as a capital letter.
Your program should run like the examples shown below.
This program encrypts a single letter. Letter: a Key: 1 Result: B
This program encrypts a single letter. Letter: a Key: -1 Result: Z
This program encrypts a single letter. Letter: f Key: 4 Result: J
This program encrypts a single letter. Letter: M Key: 6 Result: S
C++ Code:
#include <iostream>
using namespace std;
int main()
{
char letter,result;
int key;
cout<<"This program encrypts a single letter.\n\nLetter:
";
cin>>letter;
cout<<"Key: ";
cin>>key;
if(key>0)
{
if(letter>=97&&result<=122)
{
result=(letter+key-97)%26+97;
}
else
{
result=(letter+key-65)%26+65;
}
}
else
{
key=key*(-1);
if(letter>=97&&result<=122)
{
result=(letter+(26-key)-97)%26+97;
}
else
{
result=(letter+(26-key)-65)%26+65;
}
}
if(result>=97&&result<=122)
{
result=result-32;
}
cout<<"\nResult: "<<result;
return 0;
}
Code Screenshot:
Output Screenshot:
1
2
3
4