Menu
Coddy logo textTech

For Loop

Part of the Fundamentals section of Coddy's Verilog journey — lesson 58 of 90.

Loops in Verilog allow you to execute a block of code multiple times. They are especially useful in testbenches for generating repetitive test patterns, initializing memory, and iterating over arrays. Unlike hardware descriptions that run in parallel, loops execute sequentially, making them ideal for simulation and testing.

The most commonly used loop is the <strong>for</strong> loop, which repeats a specific number of times. A for loop executes a block of code repeatedly, with a loop variable that changes each iteration. You control exactly how many times it runs.

Syntax:

for (initialization; condition; increment) begin
  // Code to repeat
end
PartWhat It DoesExample
initializationSets start valuei = 0
conditionWhen to stopi < 10
incrementChanges each loopi = i + 1

Simple Example

integer i;

for (i = 0; i < 5; i = i + 1) begin
  $display("i = %d", i);
end

Output:

i = 0
i = 1
i = 2
i = 3
i = 4

The loop runs 5 times (i = 0, 1, 2, 3, 4).

For Loop in Testbenches

For loops are commonly used to test all input combinations:

reg [3:0] test_value;

for (test_value = 0; test_value < 16; test_value = test_value + 1) begin
  $display("test_value = %d", test_value);
end

This tests all 16 possible values of a 4-bit signal.

For Loop with Arrays

reg [7:0] memory [0:9];
integer i;

initial begin
  for (i = 0; i < 10; i = i + 1) begin
    memory[i] = i * 8;
  end
end

This initializes 10 memory locations.

Important Rules

RuleExplanation
Loop variable must be integer or reg Cannot be wire
Use begin/end for multiple statementsRequired for more than one line
Avoid infinite loopsMake sure condition eventually becomes false
Best used in testbenchesMost loops are not synthesizable
challenge icon

Challenge

What to do:

Add the missing for loop to print numbers from 0 to 3.

Cheat sheet

The for loop in Verilog repeats a block of code a specific number of times:

for (initialization; condition; increment) begin
  // Code to repeat
end

Example printing 0 to 4:

integer i;

for (i = 0; i < 5; i = i + 1) begin
  $display("i = %d", i);
end

Key rules:

  • Loop variable must be integer or reg (not wire)
  • Use begin/end for multiple statements
  • Ensure condition eventually becomes false to avoid infinite loops
  • Loops are best used in testbenches (mostly not synthesizable)

Try it yourself

module for_challenge;
  integer i;
  
  initial begin
    $display("Printing 0 to 3:");
    
    // TODO: Add for loop
    // Initialize i = 0
    // Loop while i < 4
    // Increment i = i + 1
    // Inside, print i
    
    $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