Facebook/LinkedIn login is now deprecated, please disconnect our access to your social profile.
Let us contribute to a cleaner Earth, Go Green Updated: May 31, 2020

Both while and do while are looping constructs that execute the given set of statements as long as the given condition is true.

A while loop first checks if the condition is true and then executes the statements if it is true. If the condition turns out to be false, the loop ends right there.

A do while loop first executes the statements once, and then checks for the condition to be true. If the condition is true, the set of statements are executed until the condition turns out to be false. If the condition is false, the loop ends right there.

So the difference between the two is that a do while loop executes the set of statements atleast once.

Syntax

  
  
	while (<condition>) begin
		// Multiple statements
	end
	
	do begin
		// Multiple statements
	end while (<condition>);

  

Example #1 - while loop

  
  
module tb;
	initial begin
		int cnt = 0;
		while (cnt < 5) begin
			$display("cnt = %0d", cnt);
			cnt++;
		end
	end
endmodule

  
Simulation Log
ncsim> run
cnt = 0
cnt = 1
cnt = 2
cnt = 3
cnt = 4
ncsim: *W,RNQUIE: Simulation is complete.

Example #2

  
  
module tb;
	initial begin
		int cnt;
		
		while (cnt != 0) begin
			$display ("cnt = %0d", cnt);
			cnt++;
		end
	end
endmodule

  
Simulation Log
ncsim> run
ncsim: *W,RNQUIE: Simulation is complete.

Example #3 - do while loop

  
  
module tb;
	initial begin
		int cnt = 0;
		do begin
			$display("cnt = %0d", cnt);
			cnt++;
		end while (cnt < 5);
	end
endmodule

  
Simulation Log
ncsim> run
cnt = 0
cnt = 1
cnt = 2
cnt = 3
cnt = 4
ncsim: *W,RNQUIE: Simulation is complete.

Example #3 - do while loop

  
  
module tb;
	initial begin
		int cnt = 0;
		do begin
			$display("cnt = %0d", cnt);
			cnt++;
		end while (cnt == 0);
	end
endmodule

  
Simulation Log
ncsim> run
cnt = 0
ncsim: *W,RNQUIE: Simulation is complete.

You consent to our cookies if you continue to use our website. To know more about cookies, see our privacy policy. I accept cookies from this site.

Agree