Skip to content
Advertisement

JavaScript, Java, Php, or C++ cipher encryption – reworking algorithm

I am trying to implement a loop that encrypts a string to the given shift amount of int shift. The code below works great, however I’d like to change the code so that it encrypts in a descending order instead of ascending. Any clues as to what to change in the algorithm?

int shift = 3;
string line = "abc";

for (int i = 0; i < line.length(); i++) {

    if (line[i] >= 'a' && line[i] <= 'z') {

        int rotate = line[i] + shift;
        if (rotate > 'z') line[i] = ((line[i] - 26) + shift);
        else line[i] = rotate;

    }

}

cout << line << endl;

With a shift of 3, the above code converts string line “abc” to “def”, but I am trying to get the output of “dcb”.

  • NOTE: The code is in C++ but I will accept JavaScript, Java, or Php suggestions just as C++, as long as it’s raw code with no library resources. Thanks guys and gals.

Advertisement

Answer

you can just upgrade the variable shift and then instead of checking overflow of increasing check the decreasing

int shift = -3;
string line = "abc";

for (int i = 0; i < line.length(); i++) {

    if (line[i] >= 'a' && line[i] <= 'z') {



        int rotate = line[i] + shift;
        if (rotate < 'a') line[i] = ((line[i] + 26) + shift);
        else line[i] = rotate;

    }

}

cout << line << endl;

you can also do the below if in your loop if you want to handle uppercases

if (line[i] >= 'A' && line[i] <= 'Z') {

        int rotate = line[i] + shift;
        if (rotate < 'A') line[i] = ((line[i] + 26) + shift);
        else line[i] = rotate;

    }
Advertisement