% vs. / beginner question

• 07-06-2010
rokraja
% vs. / beginner question
kinda new here...hello all!
Anyway i am using the book c++ without fear to learn c++ and so far it is working well but, i came across something in one of the exercises. Basically, the point of the code is to pick a random item (ball or a cube) of a random color (red, blue, green or orange). The book is trying to teach me how to set up a code so it only calls the random number generator once to select one of the 8 possibilties ( a cube of 1 of the 4 colors or a ball of 1 of the 4 colors).

Now here is the part of the code i am intrested in...the book has:

Code:

```// Draw-an-item function // Performs one item-pick by getting a random 0-4 and a random //  0-1. These are then used to index the string arrays, colors //  and shapes // void draw_an_item() {     int c;        // Random index (0 thru 4) into colors array     int s;        // Random index (0 thru 1) into shapes array     int item;     item = rand_0toN1(8);    // Get random number from 0 to 7     c = item % 4;            // c = random 0 to 3     s = item / 4;            // s = random 0 to 1     cout << colors[c] << " " << shapes[s] << endl; }```
Here is what I have ( i have different variables...sorry about that)

Code:

```void draw_an_item() {     int i;     int c;     int shape;         shape = rand_0toN1(8);         i = shape % 2;     c = shape % 4;     cout << item[i] << " of " << color[c] << endl; }```
is there any difference from the books using:
Code:

`s = item / 4;            // s = random 0 to 1`
vs my using
Code:

`  i = shape % 2;`
They both produce an answer that is between 0 and , so i dont think it matters, but i am sure you all know better.

Thanks!
~Rokraja
• 07-06-2010
Salem
Well using shape % 2; means you only end up with red balls or blue cubes (for example).
• 07-06-2010
nenpa8lo
In case of
Code:

`item/4`
you get result 0 for item 0-3 and result 1 for item 4-7. In case of
Code:

`item%2`
you get result 0 for item 0,2,4,6 and result 1 for item 1,3,5,7. Therefore final output is different in both cases.

I would also suggest to do some reading on modulo.