# Looping Statements

## While Statements

A while statement evaluates an expression and repeatedly executes the subsequent statement if the expression evaluates to true. For example:

```
ones = 0;
while (data) begin
ones = ones + data[0];
data = data >> 1;
end
```

This code counts the number of bits that are 1 in a number.

## For Statements

The for statement is used to iterate through a range of values. For example:

```
for (i=0; i<4; i=i+1)
$strobe("V(out[%d] = %rV", i, V(out[i]));
```

This is equivalent to:

```
i = 0;
while (i < 4) begin
$strobe("V(out[%d] = %rV", i, V(out[i]));
i = i + 1;
end
```

Thus, ‘i = 0’ is acting as the initializer, ‘i < 64’ the conditional that indicates the loop should continue, and ‘i = i + 1’ the incrementer.

If the index variable used is a genvar, then the loop can be unrolled in advance, which can help avoid certain restrictions on contributions and analog operators and filters. For example:

```
genvar i;
for (i=0; i<4; i=i+1)
V(out[i]) <+ transition(result & (1 << i) ? Vdd : Vss, 0, 100n);
```

This is equivalent to:

```
V(out[0]) <+ transition(result & (1 << 0) ? Vdd : Vss, 0, 100n);
V(out[1]) <+ transition(result & (1 << 1) ? Vdd : Vss, 0, 100n);
V(out[2]) <+ transition(result & (1 << 2) ? Vdd : Vss, 0, 100n);
V(out[3]) <+ transition(result & (1 << 3) ? Vdd : Vss, 0, 100n);
```

## Repeat Statements

A repeat statement evaluates an expression and then executes the subsequent statement that many times. For example:

```
ones = 0;
repeat (8) begin
ones = ones + data[0];
data = data >> 1;
end
```

The above code counts the number of ones in an 8 bit number.