Modulo Operator
Part of the Fundamentals section of Coddy's Verilog journey — lesson 20 of 90.
Another basic arithmetic operator is the modulo operator (%). It gives the remainder after division.
When you divide one number by another, the modulo operator tells you what is left over.
| Expression | Result | Explanation |
|---|---|---|
10 % 3 | 1 | 10 ÷ 3 = 3 with remainder 1 |
15 % 4 | 3 | 15 ÷ 4 = 3 with remainder 3 |
8 % 2 | 0 | 8 ÷ 2 = 4 with remainder 0 |
Code Example
module modulo_demo;
reg [7:0] result;
initial begin
result = 10 % 3;
$display("10 %% 3 = %d", result); // 1
result = 15 % 4;
$display("15 %% 4 = %d", result); // 3
result = 8 % 2;
$display("8 %% 2 = %d", result); // 0
$finish;
end
endmoduleCommon Uses
Check if a number is even or odd:
if (number % 2 == 0)
$display("Even");
else
$display("Odd");Wrap around a counter (0 to 9, then back to 0):
count = (count + 1) % 10;Get the last digit of a number:
last_digit = value % 10; // 123 % 10 = 3Challenge
Calculate the remainders for each expression.
What to do:
- Calculate
17 % 5and store inmod1 - Calculate
22 % 7and store inmod2 - Calculate
14 % 4and store inmod3
Cheat sheet
The modulo operator (%) returns the remainder after division:
10 % 3→ 1 (10 ÷ 3 = 3 remainder 1)8 % 2→ 0 (no remainder)
result = 10 % 3; // 1Common uses:
// Check even/odd
if (number % 2 == 0) $display("Even");
// Wrap counter (0–9)
count = (count + 1) % 10;
// Get last digit
last_digit = value % 10; // 123 % 10 = 3Try it yourself
module modulo_challenge;
reg [7:0] mod1, mod2, mod3;
initial begin
mod1 = ______; // 17 % 5
mod2 = ______; // 22 % 7
mod3 = ______; // 14 % 4
$display("17 %% 5 = %d", mod1);
$display("22 %% 7 = %d", mod2);
$display("14 %% 4 = %d", mod3);
$finish;
end
endmoduleThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorComparison OperatorsRecap - Simple MathBitwise Operators7Assign And Gates
Continuous AssignmentAssign With OperatorsBuilt In Gate PrimitivesAND OR NOT GatesXOR XNOR GatesRecap - Logic Gate Circuit10Decision Making
If StatementIf - ElseRecap - Simple ComparatorCase StatementCasex And CasezRecap - ALU Design5Operators Part 2
Logical OperatorsReduction OperatorsShift OperatorsConcatenation OperatorConditional OperatorRecap - Operator Challenge3Number System
Binary RepresentationSized NumbersUnsized NumbersNegative NumbersSpecial Values X And ZRecap - Number Formats6Modules
Module StructureInput And Output PortsInout PortsModule InstantiationPort Mapping By NamePort Mapping By OrderRecap - Build A Module9Procedural Blocks
Always BlockInitial BlockSensitivity ListBlocking AssignmentNon Blocking AssignmentRecap - Always vs Initial15Traffic Light Controller
Defining The StatesState Machine Logic