pter 8, we learned about a simple encryption n algorithm called a Caesar cipher
ID: 3791704 • Letter: P
Question
Explanation / Answer
The question is divided into two parts :
Before programming the solution, you must understand the Caesar Algorithm in nutshell.
Caesar Algorithm is simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on.
Thus to cipher a given text we need an integer value, known as shift which indicates the number of position each letter of the text has been moved down.
The full program is as follows (in C++):
#include <iostream>
using namespace std;
// This function receives text and shift and returns the encrypted text
string encrypt(char input[], int s)
{
string result = "";
// traverse text
int len = sizeof(&input)/sizeof(input[0]); // To know the length of the array
for (int i=0;i<len;i++)
{
// apply transformation to each character
result += char(int(input[i]+s-65)%26 +65);
}
// Return the resulting string
return result;
}
// Driver program to test the above function
int main()
{
char input[10];
int arrayCount = 0;
cout<<"Enter the Character Message Array"<<endl;
for(int i=0; i<10; i++){
arrayCount++;
cin>>input[i];
if(input[i] == '%'){
break;
}
}
cout<<"Enter Shift number"<<endl;
int shift;
cin>>shift;
cout << " Cipher: " << encrypt(input, shift);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.