0

This code is part of a program that jumbles a word. I need help understanding how the for loop is working and creating the jumbled word. For example if theWord = "apple" the output would be something like: plpea. So I want to know whats going on in the for loop to make this output.

    std::string jumble = theWord;
    int length = theWord.size();
    for (int i = 0; i < length; i++)
    {
        int index1 = (rand() % length);
        int index2 = (rand() % length);
        char temp = jumble[index1];
        jumble[index1] = jumble[index2];
        jumble[index2] = temp;
    }
    std::cout << jumble << std::endl;
kron maz
  • 131
  • 6

1 Answers1

0

I'll add comments on each line of the for loop:

for (int i = 0; i < length; i++) // basic for loop syntax. It will execute the same number of times as there are characters in the string
{
    int index1 = (rand() % length); // get a random index that is 0 to the length of the string
    int index2 = (rand() % length); // Does the same thing, gets a random index
    char temp = jumble[index1]; // Gets the character at the random index
    jumble[index1] = jumble[index2]; // set the value at the first index to the value at the second
    jumble[index2] = temp; // set the value at the second index to the vaue of the first
    // The last three lines switch two characters
}

You can think of it like this: For each character in the string, switch two characters in the string. Also the % (or the modulus operator) just gets the remainder Understanding The Modulus Operator %

It's also important to understand that myString[index] will return whatever character is at that index. Ex: "Hello world"[1] == "e"

retodaredevil
  • 863
  • 9
  • 19