Menu
Coddy logo textTech

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.

ExpressionResultExplanation
10 % 3110 ÷ 3 = 3 with remainder 1
15 % 4315 ÷ 4 = 3 with remainder 3
8 % 208 ÷ 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
endmodule

Common 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 = 3
challenge icon

Challenge

Calculate the remainders for each expression.

What to do:

  1. Calculate 17 % 5 and store in mod1
  2. Calculate 22 % 7 and store in mod2
  3. Calculate 14 % 4 and store in mod3

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; // 1

Common 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 = 3

Try 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
endmodule
quiz iconTest yourself

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

All lessons in Fundamentals