Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Recursive Functions

Verilog Functions

Example of a recursive function by computing a factorial of a number

Open in IDE
Related tutorial:
design.v
testbench.v
module tb;
  initial begin
    integer result = factorial(4);
    $display("factorial(4) = %0d", result);
  end
  
	function automatic integer factorial(integer i);
      integer result = i;
      
      if (i) begin        
      	result = i * factorial(i-1);
        $display("i=%0d result=%0d", i, result);
      end else
        result = 1;
        
      return result;
	endfunction
endmodule

/*
Simulation Log:
---------------

xcelium> run
i=1 result=1
i=2 result=2
i=3 result=6
i=4 result=24
factorial(4) = 24
xmsim: *W,RNQUIE: Simulation is complete
*/
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.