Verilog Code for Recursive Function

 Recursive Function:

Functions are normally used non-recursively. If a function is called concurrently from two locations, both the results are nondeterministic because both calls operate on the same variable space.
➢ We used keyword “automatic” to declare a recursive function.
➢ We define the top module and then the function.
➢  A condition is applied that if operand >=2, then fact=fact(operand1)*operand , otherwise fact=1;        (this is known as recursive call).
➢  Now, we have to call the function, that is, the number whose factorial we wants to display.

Verilog Code for Recursive Function:

//deine a factorial with recursive fn 
module top; //define fn 
function automatic integer factorial; 
input [31:0] oper; 
integer i; 
begin 
if (oper>=2) 
factorial=factorial(oper-1)*oper; 
// recursive call 
else  
factorial=1; 
end   
endfunction 
//call the function 
integer result; 
initial  
begin 
result=factorial(7); 
$display("factorial of 7 is %0d",result); 
end  
endmodule   

OUTPUT:


Post a Comment

0 Comments