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

foreach loop: Example #1: Single-Dimensional Arrays

SystemVerilog Control Flow & Loops

Runnable example from the SystemVerilog foreach loop tutorial (Example #1: Single-Dimensional Arrays)

Open in IDE
testbench.sv
module tb;
	int array[5] = '{1, 2, 3, 4, 5};
	int sum;

	initial begin
		// Here, "i" is the iterator and can be named as anything you like
		// Iterate through each element from index 0 to end using a foreach
		// loop.
		foreach (array[i])
			$display ("array[%0d] = %0d", i, array[i]);

		// Multiple statements in foreach loop requires begin end
		// Here, we are calculating the sum of all numbers in the array
		// And because there are 2 statements within foreach there should
		// be a begin-end
		foreach (array[l_index]) begin
			sum += array[l_index];
			$display ("array[%0d] = %0d, sum = %0d", l_index, array[l_index], sum);
		end
	end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.