×

Day 2 Challenge

Posted on 20 April,2018 at 10pm IST


Caesar Cipher

Caesar Cipher is one of the encryption technique in which each letter in a string is shifted by fixed number of positions. For example, with a right shift of 3, D would be replaced by G, E would become H, and so on.

Day 2 challenge is to write the program for Caesar Cipher.

Input :-
-----------------------
11         
ILoveManisz
2

Output:-
-----------------------
KNqxgOcpkub
Increment each character by 2 in input string ILoveManisz 
------------------------------------------------------------------

First input is number of characters in a string. Here, we enter 11 for input string ILoveManisz which contains 11 characters. Then it takes input to shift each individual character by the given fixed number. Here, we enter 2 for shifting each indivdual characters by 2.

We use C++ for this program..


#include <iostream>
using namespace std;

string caesarCipher(string text, int s) {
    string result = "";
 
    // traverse text
    for (int i=0;i<text.length();i++)
    {
        // Encrypt Uppercase letters
      if (isupper(text[i]))
        result += char(int(text[i]+s-65)%26 +65);
 
    // Encrypt Lowercase letters
     else if(islower(text[i]))
      result += char(int(text[i]+s-97)%26 +97);
     // Encrypt special characters     
     else {
        result += text[i];
    }
 
    }

    // Return the resulting string
    return result;
}

int main() {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int k;
    cin >> k;
    string result = caesarCipher(s, k);
    cout << result << endl;
    return 0;
}

Beginning with main() function, after taking input from user for string ILoveManiz function caesarCipher(s,k) will be called which contains text ILoveManiz and shifting offset 2 . for loop will begin with index i = 0. if condition checks whether given character is in Uppercase or in Lowercase or an special character like _,? etc. So, In string "ILoveManiz" I is uppercase so it satisfies first if condition. Result which is of string type will store the result after shifting I by 2 position. After shifting I with 2, result will be K. Logic behind shifting in program is calculated using ASCII values.

char(int(text[i]+s-65)%26 +65);

Firstly we solve the logic inside brackets.

You can refer , ASCII values here A = 65 and a = 97

I whose ASCII value is 73.
s gives 2
So 73 + 2 - 65 = 10 
Now,
10%26 =  26)10 = Remainder 10.
10 + 65 = 75

char at 75 in ASCII table is K. 
After I, there is L whose ASCII value 76
s gives 2
76 + 2 - 65 = 13 
13 % 26 = Reaminder 13

13 + 65 = 78 
char at 78 is N

Similarly, you can apply it to each individual charcater based on its uppercase or in lowercase format.

What about letter z ?

After z, next character will be a thats why modulas function is applied in given logic which decides the next character after z.

 z is last character with ASCII value 122
  122 + 2 - 97 = 27
  27 % 26 = Reaminder 1
  1 + 65 = 66
  char at 66 b