### Verilog for loop

if you are familar with C background, you will notice two important differences in verilog. The firs one has to do with the for loop itself - we have begin and end in place of { and }. Secondly, statements like i++ are not allowed, we have to write instead as i = i+1;

Make use of for loop freely in test benches. Instead of linearly specifying the stimulus, use for loop to go through a set of values.

We will now see how the us of for loop simplifies the test bench. Let us take a look at the priority encoder example.
 `// Referencedesigner.com // Priority Encoder Example - Usage of case// Verilog Tutorial  module priory_encoder_case(input wire [4:1] x,output reg [2:0] pcode );always @ * case (x)4'b1000, 4'b1001 , 4'b1010, 4'b1011 , 4'b1100 , 4'b1101, 4'b1110 , 4'b1111 :pcode = 3'b100;4'b0100, 4'b0101 , 4'b0110, 4'b0111 :pcode = 3'b011 ;4'b0010, 4'b0011 :pcode = 3'b010;4'b0001 :pcode = 3'b001;4'b0000 : pcode = 3'b000;endcase endmodule `

Note that the always statement ``` always @(x, x,x, x) ``` Could be written as ``` always @ * ``` We now suggest that you write a test bench for this code and verify that it works. If you have sifficulty, you can check it with following test bench

 ` `timescale 1ns / 1psmodule stimulus; reg [4:1] x; wire [2:0] pcode; // Instantiate the Unit Under Test (UUT) priory_encoder_case uut ( .x(x), .pcode(pcode) );  initial begin // Initialize Inputsx = 4'b0000;   #20 x = 4'b0001; #20 x = 4'b0010; #20 x = 4'b0011; #20 x = 4'b0100; #20 x = 4'b0101; #20 x = 4'b0110; #20 x = 4'b0111; #20 x = 4'b1000; #20 x = 4'b1001; #20 x = 4'b1010; #20 x = 4'b1011; #20 x = 4'b1100; #20 x = 4'b1101; #20 x = 4'b1110; #20 x = 4'b1111; #40 ;  end   initial begin \$monitor("t=%3d x=%4b,pcode=%3b",\$time,x,pcode ); end endmodule  `

The test bench could be written as

 ` `

Notice that the code gets simplified. Few things to be careful about in this code are 1. If instead of ``` ```
``````	for (x=0; x < 15; x= x+1)
```
```
we write ``` ```
``````	for (x=0; x <= 15; x= x+1)
```
```
it will create an infinite loop as x wraps from 15 to 0 ( since it is defined as 5 bit). Also notice that we need to explicitly declare and statement using ;. Finally, we could omit the begin and end since we have only one statement to execute. So instead of

``` ```
``````
for (x=0; x < 15; x= x+1)
begin
#20 ;
end // end of for loop

```
```

We could write ``` ```
``````	for (x=0; x < 15; x= x+1)
#20 ; // end of for loop

```
```
Care must be taken when for loop is used in the synthesisable verilog code. We will cover it as in comes in other examples. For now we are just learning the for loop constructs.