Prev Problem
Next Problem

55. MUX Tree using Loops

module mux8_tree (
    input  [7:0] d,
    input  [2:0] sel,
    output       y
);
    reg [3:0] l0;
    reg [1:0] l1;
    reg       l2;

    integer k;

    always @* begin
        // L0: 8 -> 4 (use sel[0])
        for (k = 0; k < 4; k = k + 1)
            l0[k] = sel[0] ? d[2*k+1] : d[2*k];

        // L1: 4 -> 2 (use sel[1])
        for (k = 0; k < 2; k = k + 1)
            l1[k] = sel[1] ? l0[2*k+1] : l0[2*k];

        // L2: 2 -> 1 (use sel[2])
        l2 = sel[2] ? l1[1] : l1[0];
    end

    assign y = l2;
endmodule

💡Remember

  • for loops with constant bounds are unrolled into real hardware → here, a balanced 2:1 mux tree (3 levels).
  • Ternary operator ?: acts as 2:1 mux
  • Using staged temps (l0, l1, l2) keeps logic depth predictable and avoids accidental priority chains.
  • This is functionally equivalent to y = d[sel], but written to practice tree construction with loops.