Logo

Programming-Idioms

  • Ruby
  • D

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Control flow jumping forward after the end of the outermost loop
import std.writeln;
outer:
foreach (i; 0 .. m.length)
{
	foreach (j; 0 .. m[i].length)
	{
		if (m[i][j] < 0)
		{
			writeln(m[i][j]);
			break outer;
		}
	}
}

D has labeled break and continue statements.
negative_value = catch :negative do
  matrix.each do |row|
    row.each do |value|
      throw :negative, value if value < 0
    end
  end
end

puts negative_value
Outer_loop:
for A in M'Range (1) loop
   Inner_Loop:
   for B in M'Range (2) loop
      if M (A, B) < 0 then
         Put_Line (M (A, B)'Image);
         exit Outer_Loop;
      end if;
   end loop Inner_Loop;
end loop Outer_Loop;

New implementation...
< >
programming-idioms.org