• ### Announcements

GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Followers 0

# Modulus Operator Usage

## 16 posts in this topic

Ok, I guess this could be a bit of a math question so if he mods want it there then I understand. Just posted it here as I'm trying to understand it.

Well I understand it. As in I know when it is used what it is doing. I understand its giving me the remainder of two numbers being divided. That's easy enough. My question is more along the lines of, how do you know when to use it? Yes I know when I need to know or get the remainder but how/when do I really need to do know this on calculations? How do I know I need to use it here? I see some examples of code and they say "a simple modulus operator will give us what we need. I guess when I sit and actually work it out like it was a math problem I see how it helps. Though if I was just trying to solve a problem on my own I would never think to use it really.

Maybe it is because Math isn't my best subject, though I'm not terrible at it, mostly a B student in it. I mean I've gotten myself through Calculus 1, Calculus 2, Probability, and Linear Algebra (know a little bit already) next semester. Though I just can't quite ever see "ok this problem needs to be solved by the modulus operator." I guess I could see a problem here or there that I know I'd use it (could see it helping when doing some unit conversions) but then again I know that because I have basically been told it's used here.

So how do I know or figure out really when to use it?

Thanks to all who help.
0

##### Share on other sites

You can also use it to bring a random int into a range:

int n = intrand(); //gives random value between 0 and a bajillion
n %= MY_ MAX_RAND; //brings the value into the range 0 to MY_MAX_RAND

The circular sequence behavior that ultramailman pointed out can be useful in many situations:
//pseudocode
int n = 0;
loop {
n %= 5;
print(n++);
}
0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0.....

Actually HUGE thank you for this.  Just yesterday I was dealing with that and I ended up writing a simple if statement to reset it!  I don't think I would have ever thought about using the modulus operator there.  Thanks.

Hodgman: That's an interesting example also because I was working out a formula for that the other day.  Interesting I ask about this and I immediately get like two examples that I've dealt or thought of.

On what you said about "how do you know when to use addition or division?"  That is an interesting question to pose.  I would say just because it was drilled into our minds so much in school that you learn to use it while using the modulus isn't really drilled into your mind to use in school.  Only reason I can think of I guess...?

Thanks everyone!

1

##### Share on other sites

Some practical everyday uses:

// I want to trigger something every 7 executions:

static int count = 0;

count = ++count % 7;

if( !count ) {do something}

// I want to cycle 0-6 repeatedly.

static int count = 0;

count = ++count % 7;

In the first case the 'if' relies on the fact that the only "true" condition is when something is non-zero.  In the second case a value modded by any higher value results in the same value, it goes to zero when modded with itself.  Basically a variable in both cases is going to step from 0 to mod value minus one, or 0-6 in this case and keep repeating.

I think I use the first case with the 'if' statement more often but I know I use the second case on occasion also.

Edited by AllEightUp
0

##### Share on other sites

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.

'true' is typically nonzero, isn't it? In c/c++ it would be "if(!count) {stuff}".
#include <iostream>

int main() {
//print multiples of 5 up to 100
for(int n = 1; n <= 100; ++n) {
if(!(n % 5)) {std::cout << n << std::endl;}
}
}

Is zero true in java or something?

Also, addressing the general topic, if you're wanting both the quotient and the remainder then check to see if there's an intrinsic that can give you both results without having to do the division twice. When the CPU does integer division it actually produces both results, regardless of whether you asked for division or modulus. It's not a huge issue, but division is the heaviest integer math operation for the cpu by a wide margin, so in anything where performance matters it can be good to know if there's an intrinsic. (Don't prematurely optimize, but don't prematurely pessimize either.)

Edit: Apparently there's one in std::div, which is convenient, but poking around for a minute I see that it's common for modern compilers to optimize this problem away in most cases. Edited by Khatharr
0

##### Share on other sites

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.

'true' is typically nonzero, isn't it? In c/c++ it would be "if(!count) {stuff}".
#include <iostream>

int main() {
//print multiples of 5 up to 100
for(int n = 1; n <= 100; ++n) {
if(!(n % 5)) {std::cout << n << std::endl;}
}
}

Is zero true in java or something?

Blah, sorry....  Typo, "non-zero".. :)

0

##### Share on other sites

Some practical everyday uses:

// I want to trigger something every 7 executions:

static int count = 0;

count = ++count % 7;

if( count ) {do something}

// I want to cycle 0-6 repeatedly.

static int count = 0;

count = ++count % 7;

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.  In the second case a value modded by any higher value results in the same value, it goes to zero when modded with itself.  Basically a variable in both cases is going to step from 0 to mod value minus one, or 0-6 in this case and keep repeating.

I think I use the first case with the 'if' statement more often but I know I use the second case on occasion also.

EDIT: Nvm, no reason for this post I guess.  lol.  Typo.  :)

Like Khatharr said, in C/C++ it would actually execute every time except when count is 0.

As a quick test:

for(index = 0; index < 10; ++index)
{
count = ++count % 7;
if(count)
{
std::cout << count << " ";
}

}



produced output:

1 2 3 4 5 6 1 2 3

0

##### Share on other sites

ike Khatharr said, in C/C++ it would actually execute every time except when count is 0.

As a quick test:

for(index = 0; index < 10; ++index)
{
count = ++count % 7;
if(count)
{
std::cout << count << " ";
}

}



produced output:

1 2 3 4 5 6 1 2 3


Yup, I goofed..  Please don't hang me at the weekly horribly backwards post meeting GameDev holds every week.

Edited by AllEightUp
0

##### Share on other sites

talking

Blah, sorry....  Typo, "non-zero"..

No worries. It's a good point you brought up.
0

##### Share on other sites

Also, addressing the general topic, if you're wanting both the quotient and the remainder then check to see if there's an intrinsic that can give you both results without having to do the division twice. When the CPU does integer division it actually produces both results, regardless of whether you asked for division or modulus. It's not a huge issue, but division is the heaviest integer math operation for the cpu by a wide margin, so in anything where performance matters it can be good to know if there's an intrinsic. (Don't prematurely optimize, but don't prematurely pessimize either.)

Edit: Apparently there's one in std::div, which is convenient, but poking around for a minute I see that it's common for modern compilers to optimize this problem away in most cases.

I was sort of going to "ask" about that.  I knew that division was the "heaviest" integer math for the most part.  So I was going to ask if the CPU did something to store both results.  though I didn't want to seem like I was trying to "optimize" something or anything like that.  I was going to ask out of curiosity.  Though felt like it could go beyond this topic and didn't want to get into premature optimization.  lol.  Just my nerd curiosity.  :)  Thanks.

Some practical everyday uses:

// I want to trigger something every 7 executions:

static int count = 0;

count = ++count % 7;

if( count ) {do something}

// I want to cycle 0-6 repeatedly.

static int count = 0;

count = ++count % 7;

In the first case the 'if' relies on the fact that the only "true" condition is when something is zero.  In the second case a value modded by any higher value results in the same value, it goes to zero when modded with itself.  Basically a variable in both cases is going to step from 0 to mod value minus one, or 0-6 in this case and keep repeating.

I think I use the first case with the 'if' statement more often but I know I use the second case on occasion also.

Like Khatharr said, in C/C++ it would actually execute every time except when count is 0.

As a quick test:

for(index = 0; index < 10; ++index)
{
count = ++count % 7;
if(count)
{
std::cout << count << " ";
}

}



produced output:

1 2 3 4 5 6 1 2 3


Yup, I goofed..  Please don't hang me at the weekly horribly backwards post meeting GameDev holds every week.

I won't...to much.  :).

I saw your new post after I posted mine, so I edited.  Gamedev didn't notify me of a new post with the code editor up.  Or i didn't see it.  lol.  :)

0

##### Share on other sites

EDIT: Nvm, no reason for this post I guess.  lol.  Typo.

Like Khatharr said, in C/C++ it would actually execute every time except when count is 0.

Actually, this is a good case of a bad code typo and use case.  The fact that I got the example wrong led me to describe the wrong case and I didn't even notice it and I'm a pretty annoying person about details like that.....  It leads me to suggest any use of modulus should probably be documented with a comment as to the expectations.. :)

0

##### Share on other sites

You can use mod for "wrapping values":

#include <iostream>
#include <string>
using namespace std;

enum DaysOfWeek
{
Sunday = 0,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};

int main()
{

int input;
cout << "Enter a number for the day of the week you want: ";
cin >> input;
if(input>6)
input = input % 7;
if(input<0)
input = (input % 7) + 7;

string result;

switch(input)
{
case Sunday:
result = "Sunday";
break;
case Monday:
result = "Monday";
break;
case Tuesday:
result = "Tuesday";
break;
case Wednesday:
result = "Wednesday";
break;
case Thursday:
result = "Thursday";
break;
case Friday:
result = "Friday";
break;
case Saturday:
result = "Saturday";
break;
}

cout << result << endl;

cin.sync();
cin.ignore();

return 0;
}

0

##### Share on other sites

Careful now...

    if(input>6) //this condition is (usually) not an effective optimization and is mathematically irrelevant
input = input % 7;
if(input<0)
input = (input % 7) + 7; //this is incorrect in cases where input == n * -7

Try:

    input %= 7;
if(input<0)
input +=  7;
Edited by Khatharr
1

##### Share on other sites

Careful now...

    if(input>6) //this condition is (usually) not an effective optimization and is mathematically irrelevant
input = input % 7;
if(input<0)
input = (input % 7) + 7; //this is incorrect in cases where input == n * -7

Try:

    input %= 7;
if(input<0)
input +=  7;

(In fact I think I did predict it but messed up my conditionals...  gotta be careful when coding)

Edited by lightxbulb
0

## Create an account

Register a new account