### Array problem

So lets say I have an array like string letters{a,b,c,d,e,f,g,h,i,h,j,k...etc}(no parentheses for ease of explaining problem) and I wanted the user to enter a letter. They program would take the letter and then move it...lets say 5 letters up..so a A becomes a F etc..

Would you create a loop to find the location of the users inputed letter and then add (lets say 5 letters up) so the program finds out the location of the letter in the array and then adds 5 to it...How would the loop be coded?
Remember, characters are numbers, too. So we can do some arithmetic on them.
 ``123`` ``````... std::cout << 'a' + 5; //legal ...``````

So you want to add 5 to each letter in your array. A naive approach would be as follows:
 ``123456`` `````` char myArray[6] = {'a', 'e', 'i', 'o', 'u', 'y'}; for(int i = 0; i < 6; i++) { char newChar = myArray[i] + 5; std::cout << newChar; }``````

But check the output:
 ``` fjntz~ ```

Most of the letters are fine... but what about the last one? It comes out as '~' but you probably want 'd'. We want to stay within the alphabet, so get familiar with the modulo (%) operator. See if that's enough to get you started.

EDIT:
If you haven't seen modulo before, check out this code to see how it can be used to 'wrap around' the end of an array instead of running off the end of my array and blowing stuff up.
 ``12345678`` `````` const int arraySize = 6; char myArray[arraySize] = {'a', 'b', 'c', 'd', 'e', 'f'}; int numberThatsWayBiggerThanArraySize = 30; for(int i = 0; i < numberThatsWayBiggerThanArraySize; i++) { std::cout << myArray[i % arraySize]; }``````
Last edited on
Topic archived. No new replies allowed.