I want to break from loop as soon as condition is satisfied

class packet;

rand bit bench_row1 [3][2];
  
function void display();
  $display("no of students in first group",bench_row1);

//$display("student is[1] %s  =",);
$display("---------------------------------------------------");
endfunction

function void post_randomize();
 bench_row1 = '{ default:0};
 
  
 while(bench_row1.sum() < 2)

              begin        
            bench_row1[$urandom_range(2,0)][$urandom_range(1,0)] = $urandom_range(1,0);
            $display("inside while looppppppppppppppppppppppp",bench_row1);
            if(bench_row1.sum() == 2) break;
             end 

/*  
  if(bench_row1.sum() < 3) 
    do begin
    bench_row1[$urandom_range(2,0)][$urandom_range(1,0)] = $urandom_range(1,0);
      $display("inside if looppppppppppppppppppppppp",bench_row1);
    end while( bench_row1.sum() != 2);
 */ 
    
 endfunction
                                                    
                                                      
                                                    
endclass

module ex;
packet pkt;
initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endmodule	

i tried it with if and while loop, output i am getting is infinite times. actually it is not going inside if loop. how to break loop if condition bench_row1.sum() = 2 satisfies?

In reply to swapnilsrf9:
The problem is in the way that you are using the sum() reduction method, actually, two problems.

The first is that the sum() method is only defined two work on one dimension at a time, with each element in that dimension having an integral type.
bench_row1.sum()
tries to sum up 3 elements where each element is an unpacked array of 2 bits. The return type of of the sum method is the same type as each array element, and you can add unpacked arrays.

Which brings me to your second problem. Even if
bench_row1
had a single unpacked dimension, the result of the sum() method is the same type as each element, a single bit in this case. So there is no way the result could ever be decimal 2.

The way to use reduction operators with multi-dimensional arrays is by using the with clause to cast each element into an integral type.

bench_row1.sum(ii) with ( ii.sum(jj) with ( int'(jj) ) )

See 7.12.3 Array reduction methods in the 1800-2012 LRM for full explanation.
If you just want to count the number of bits set in any bit-stream variable, SystemVerilog provides a built-in function:

 $countones(bench_row1)

In reply to dave_59:

thank you sir.