HDLbits
Start Practicing

Verilog Language/Procedures

Population Count (for loop)

medium
proceduresalways-blockfor-looppopcount

for loops inside procedural blocks let you describe repetitive combinational logic (like scanning every bit of a vector) without writing it out by hand. Since the loop is inside an always @(*) block, it still synthesizes into pure combinational logic — the loop is “unrolled” at compile time, not executed at simulation runtime like software.

Build a circuit with an 8-bit input in and a 4-bit output count equal to the number of bits in in that are 1 (the population count, or “popcount”).

Interface

Signal Direction Width Description
in input 8 Input vector
count output 4 Number of 1 bits in in (0 to 8)

Example

If in = 8'b10110100, there are four 1 bits, so count = 4'd4.

Notes

  • Declare a loop variable (integer i;) outside the always block (in Verilog, for loop variables inside always @(*) must be declared as module-level integers, not inside the loop itself).
  • Initialize count = 0 at the top of the always block before accumulating, since procedural blocks don’t automatically reset between evaluations.
  • 4 bits is just enough to represent counts from 0 to 8 inclusive (4'd8 = 4'b1000).