Public Group

# Total newbie

This topic is 3795 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I have been learning C++ for 3 days now, so I am still very noob. I have started to work through a book by Michael Dawson, "Beginning C++ Game Programming". There is one bit of code I cant understand any help would be very welcome! So this is part of a word game where the program randomly picks a word and then rearranges it, for the user to figure out. This is the part where it rearranges the word it picked, wich i do not understand... :( please help! string jumble = theWord; //the word is the picked word int length = jumble.size(); //jumble is the rearranged version 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; }

##### Share on other sites
make a copy of the word, call it 'jumble'count the letters in 'jumble', call it 'length'repeat the following 'length' times{        get a random number from 0 to 'length', call it 'index1'        get a random number from 0 to 'length', call it 'index2'        swap the letter at position 'index1' in jumble with the letter at 'index2' in jumble}

I'm guessing that the bit that confused you was the '%' sign?
"%" is the modulo operator. The % operator goes hand-in-hand with the / operator (division). It returns the remainder of the division of the left/right values.
e.g. 24 divided by 10 is equal to 2 and 4 remainder, or in code:
24 / 10 == 2
24 % 10 == 4

So back to your code, "rand() % length" gives us a random number from 0 to length, because "rand()" gives us a random number from 0 to [really big number], then you divide it by 'length' and find the remainder, which is guarenteed to always be bigger or equal to 0 and smaller than 'length'.

N.B. This is only true for integer math though (i.e. when you're using variables of type 'int' or similar). The % operator cannot be used for floating-point math.
e.g.
24.0f / 10.0f == 2.4f

To find the remainder of a floating-point division, you'd have to do it yourself:
float div = 24.0f / 10.0f;//2.4f
float mod = (div - int(div)) * 10.0f; //4.0f

##### Share on other sites
try telling us what you think is happening so we can help or tell us what you don't understand so we can explain.

##### Share on other sites
btw has anyone worked through this book, if so is it a good place to start?
thx Hodgman, I get it now.

##### Share on other sites
i started with that book and i found a very good place to begin.

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 17
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631758
• Total Posts
3002163
×