Modulo (%) Operator

2025/12/27

Type
Learning Resource
Format
Glossary Article
Version
General
Subject Tags
Code
Assets
All else
Copyright 2016-2026, GDQuest
Created
2026/02/16
Updated
2025/12/27

Modulo (%) Operator

The % operator is called the "Modulo" operator.

It is used to return the remainder of a division. For example:

How does that help anything, why do I need it?

We mostly use it in two cases:

  1. We want to know if a number is even or odd; we can use % 2, and see if we obtain 0 (even) or 1 (odd).
  2. We want to wrap a number over a range.

The second one is complicated to wrap your head around, so here's a demonstration.

Suppose we have an array of 4 items, and we want to continuously pick a valid index by incrementing an index.

var letters := ["a", "b", "c", "d"]
var initial_index := 0

func get_next() -> void:
	var next_initial_index := initial_index + 1
	initial_index = next_initial_index % letters.size()

When I run get_next() the first time, next_initial_index becomes 1.

We know letters.size() is 4. If we run modulo on next_initial_index, we obtain still just 1.

1 % 4 returns 1, because 1/4 gives us 0 and the remainder is 1.

When we increment next_initial_index we obtain 2. 2 % 4 gives us 2.

And so on, until 4. What does 4 % 4 return? Yes, the result of the division 4 / 4 is 1, and the remainder is 0.

What does 5 % 4 return? That's right, 1! And 6 % 4 return? That's right, 2!

And so on. No matter how much we increment next_initial_index, we obtain a result between 0 and 3. The index will always be valid.

Become an Indie Gamedev with GDQuest!

Don't stop here. Step-by-step tutorials are fun but they only take you so far.

Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.

Nathan

Founder and teacher at GDQuest
  • Starter Kit
  • Learn Gamedev from Zero
Check out GDSchool

You're welcome in our little community

Get help from peers and pros on GDQuest's Discord server!

20,000 membersJoin Server

Contribute to GDQuest's Free Library

There are multiple ways you can join our effort to create free and open source gamedev resources that are accessible to everyone!