Question

So more or less I'm attempting to write a simple encryption/decryption program in C++. Right now i have most of the other basic functions wrote. Although, I'm unsure how to integrate arrays into exactly what I want it to do.

This is my first program in c++ so bear with me.

Basically, i want the user to enter a set of characters a through z and A through Z I want to use an array to assign each letter a value, IE referenceArray[] = {'a', 'b', 'c', ... 'A', 'B', 'C'} Where each of these characters hold the value of their position in the array a = 0, b = 1, etc. So when the user enters phrase, entArray[], it echoes the phrase back for verification, then using the formula 51 - (theValueOf_enteredArray[0]) where 51 is max value being the theValueOf_entArray[0] being based on the values assigned in referenceArray[] and then I want it to loop and repeat this action for the next character in enteredArray.

So essentially just to clarify exactly what i want the output to be, if a = 0 and Z = 51

and user entered: abcdeA the output would be: ZYXWVz

if anybody can help, i can send you what i have right now, but like i said it's all the other portions of the program that i'm required to have, this is the last part and it's really got me stumped, really just the syntax of the math involved

Was it helpful?

Solution

You can loop over the entry array and once know the index of the current letter, apply the transformation to it:

for (int i=0; i<SIZE && entArray[i] != '\0'; ++i) {
  char letter = entArray[i];
  char transformedChar = letter;
  int entIdx = getIndex(letter);
  if (entIdx >= 0) {
    int transformedIdx = 51 - entIdx;
    transformedChar = referenceArray[transformedIdx];
  }
  cout << transformedChar;
}

where SIZE is the size of entArray. You might want to use a named constant for 51 as well.

Here we first assume that the current letter cannot be transformed (entIdx < 0), if this assumption is false, apply the transformation and get the letter at the transformed location

To get the index of a letter in the reference array:

int getIndex(char letter) {
  for (int i=0; i < 51; ++i) {
    if (referenceArray[i] == letter) {
      return i;
    }
  }
  // could not find the letter (e.g. space):
  return -1;
}

Note: you might want to create and populate a map from letter to index as well to make the lookup easier -- you could use a map<char, int>, for instance

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top