Programming Short – Back to the Future with Modulo


With all this Back to The Future talk this week it hit me that it’s been a while since I last made a programming blog post.

Today we’ll quickly take a look at a useful use of modulo (%) to keep something from staying within a range. Modulo mathematically returns the remainder of a division. So 10 % 4 returns 2 (4 fits twice in 10 (i.e up to 8) , what remains is 2). When the first number before the modulo is lower than the second one, you just get the number back. 4 % 10 equals 4 (logical as 10 doesn’t fit in 4, so nothing happens and there’s still just 4)

Applying this in programming (C++ this time) we could use this to make sure a certain number stays within a range, have a look:

int maxPoints = 4;
int nextPoint = 0;
void MoveToNextPoint()
int incrementedPoint = nextPoint + 1; //cached value only for the description
nextPoint = incrementedPoint % maxPoints;

printf("%d (Calculation: %d %% %d) \n", nextPoint, incrementedPoint, maxPoints);

Every time this function is called we move to the next point, however when working with indexes and being lousy the point could be going over the maximum number of points we have. You could write a condition that checks if the point is going out of range, but we can write that faster and without using a branch, and I’m lazy so why not.

Instead “nextPoint = incrementedPoint % maxPoints;” makes sure the point never goes out of bounds. Say our point index is 5, but we have a maximum of 4 points. Filling in these numbers our nextPoint would be 5 % 4 which in turn is 1. 6 % 4 = 2, and so on. We essentially can keep going and never go over the maximum bounds without having to use if checks, making for clean and fast code.

In video gaming  programming you’ll often see this piece of code return during spritesheet animations, where this is used extensively to loop frames of an animation.

Pointless blogpost? Maybe. I’ll try to feature better Programming Shorts in the future, but I also want to point out some common video game programming things beginning programmers will definitely come across. Besides, it’s good practice to keep your code clean.

Nick out!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s