VB.NET Mod Operator

The VB.NET programming language

How can you use modulo division in the VB.NET language? With the Mod operator, you can compute the remainder of a division expression. Mod is equivalent to the % operator in C-like languages.

This VB article demonstrates the Mod operator used with constants. It uses Mod in a loop construct.

Mod expressions

This example shows some Mod expressions with constant Integers. When the value 90 goes into 1000 11 times, but leaves a remainder of 10. This is the result of 1000 Mod 90. The next Mod expressions show the same principle in action and it is clearest if you read the result of the program.

Program that uses Mod with constants [VB.NET]

Module Module1
    Sub Main()
	' Compute some modulo expressions with Mod.
	Console.WriteLine(1000 Mod 90)
	Console.WriteLine(100 Mod 90)
	Console.WriteLine(81 Mod 80)
	Console.WriteLine(1 Mod 1)
    End Sub
End Module

Output

10
10
1
0

Mod loop

Programming tip

Using a Mod expression is appropriate in a For loop. You can apply Mod to the induction variable i. In this program, we display i whenever it is divisible by 10.

Program that uses Mod in For loop [VB.NET]

Module Module1
    Sub Main()
	' Loop through integers.
	For i As Integer = 0 To 200 - 1
	    ' Test i with Mod 10.
	    If i Mod 10 = 0 Then
		Console.WriteLine(i)
	    End If
	Next
    End Sub
End Module

Output

0
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190

Summary

.NET Framework information

Modulo division is an important concept to understand in computer programming. In the .NET Framework, modulo division is used to implement collections such as Dictionary, which are very useful. The Mod operator often comes in handy whenever a mathematical procedure is needed.

VB.NET Tutorials
.NET