SourceSV Verification Directory

While and Do While

While and do while loops are used for iterative control structures that execute a block of code multiple times based on a condition. These loops are particularly useful when the number of iterations is not known beforehand and depends on the evaluation of the loop condition.

While Loop

The “while” loop executes a block code until the specified condition is true. The condition is evaluated before each iteration.

Syntax

while (condition) begin
   // execute the code
end

Example Code: While Loop

module tb_while_loop;

  initial begin

    int i;

    $display("---------- While Loop ----------");
    while (i<16) begin
      $display("I = %0d", i);
      i = i + 1;
    end

  end

endmodule

Do While Loop

The “do while” loop differs from the while based on the evaluation of the condition. In the “do while” loop the block of code is executed once before the condition is evaluated.

Syntax

do begin
   // execute the code
end

Example Code: Do While

module tb_do_while_loop;

  initial begin

    int i;

    $display("---------- Do While Loop ----------");
    do begin
      $display("I = %0d", i);
      i = i + 1;
    end while (i<16);

  end

endmodule