Menu
Coddy logo textTech

While Loop

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

The while loop repeats a block of code as long as a condition is true. Unlike the for loop, it does not have a built-in counter — you must update the loop variable yourself.

A while loop checks a condition before each iteration. If the condition is true, the loop executes. If false, the loop stops.

Syntax:

while (condition) begin
  // Code to repeat
end

Simple Example

integer i = 0;

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

Output:

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

The loop runs as long as i < 5.

While vs For Loop

 For LoopWhile Loop
CounterBuilt-inYou manage it
When to useKnown number of iterationsUnknown when loop will stop
Syntaxfor (i=0; i<5; i=i+1)while (i < 5)

While Loop in Testbenches

While loops are useful when you don't know exactly how many iterations you need:

integer i = 0;

while (i < 16) begin
  $display("Testing value %d", i);
  i = i + 1;
end

Finding a Specific Value

integer i = 0;
reg [7:0] data;

while (data[i] != 1) begin
  i = i + 1;
end
$display("First 1 found at position %d", i);

Important Rules

RuleExplanation
Condition must become falseOtherwise infinite loop
Update loop variable insideOr loop never ends
Loop variable must be integerCannot be reg
Use begin/end for multiple statementsRequired for more than one line
challenge icon

Challenge

What to do:

Add the missing while loop to print numbers from 0 to 2.

Cheat sheet

The while loop repeats a block of code as long as a condition is true. You must update the loop variable manually.

integer i = 0;

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

Key rules:

  • Loop variable must be integer (not reg)
  • Always update the loop variable inside the loop to avoid infinite loops
  • Use begin/end for multiple statements

While vs For: Use for when the number of iterations is known; use while when the stop condition is dynamic (e.g., searching for a value).

// Finding first set bit
while (data[i] != 1) begin
  i = i + 1;
end

Try it yourself

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