Menu
CoddyTech

Modulo Operator

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 17 of 92.

The modulo operator % gives the remainder of a division:

var result := 10 % 3 # 1

3 fits into 10 three times (9), and 1 is left over.

When the first number is smaller than the second, the whole first number is left over: 5 % 8 is 5.

Modulo tells you whether a number is even. An even number leaves 0 when divided by 2, and a positive odd number leaves 1. The == operator checks whether two values are equal:

var n := 14
print(n % 2 == 0) # true, 14 is even

With a negative first number, the remainder is negative too: -7 % 3 is -1.

In GDScript, % works with integers only. For floats, use fmod(): fmod(7.5, 2) is 1.5.

challenge icon

Challenge

Easy

Declare three variables a, b and c with the values 9, 2 and 11.

Then declare three more:

  • d that holds a modulo 2
  • e that holds b modulo 3
  • f that holds c modulo 10

The print() lines are already there and output:

a = 9
b = 2
c = 11
d = 1
e = 2
f = 1

Try it yourself

extends Node

func _ready():
	# Declare your variables below

	# Don't change the lines below
	print("a = ", a)
	print("b = ", b)
	print("c = ", c)
	print("d = ", d)
	print("e = ", e)
	print("f = ", f)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler