Home » Technical Interview Questions » String Interview Questions » Caesar Cipher

# Caesar Cipher

## The Caesar Cipher technique is one of the earliest technique of encryption.

That is,

Ex(x) = (x + n)mod26
Here, for each letter in the given text it is replaced by a letter some fixed number of positions down the alphabet. If n = 1, replace A with by B, B would become C and so on.

Here, a = 0, b = 1, ……. z = 25

### Example

Text : “ABCD”
Shift : 2

Output : “DEFG”

Time complexity : O(n)

## Algorithm

Here a string of lower case or upper case letters is Text and integer between   – 0 – 25 is Shift

1. Traverse the input string.

2. Take one character at a time, for each character transform it as per the rules.

3. Return the final string.

## C++ Program

```#include <bits/stdc++.h>

using namespace std;

string transform(string Text, int Shift)
{
string output = "";
for (int i=0; i<Text.length(); i++)
{
if (isupper(Text[i]))//upper case
{
output = output + char(int(Text[i]+Shift-65)%26 +65);
}
else//lower case
{
output = output + char(int(Text[i]+Shift-97)%26 +97);
}
}
return output;
}

//Main function
int main()
{
string Text="AbCdEf";
int Shift = 4;
cout<<"Text: "<<Text<<endl;
cout<<"Shift: "<<Shift<<endl;
cout<<"Output: "<<transform(Text, Shift);
return 0;
}```