Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

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
from itertools import chain
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
    print(next(i for i in chain.from_iterable(matrix) if i < 0))
except StopIteration:
    pass
def loop_breaking(m, v): 
    for i, row in enumerate(m): 
        for j, value in enumerate(row): 
            if value == v: 
                return (i, j)
    return None

print(loop_breaking(([1,2,3],[4,5,6],[7,8,9]), 6))
b = False
for r in m:
    for i in r:
        if i < 0:
            print(i)
            b = True
    if b: break
class BreakOuterLoop (Exception): pass

try:
    position = None
    for row in m:
        for column in m[row]:
            if m[row][column] == v:
                position = (row, column)
                raise BreakOuterLoop
except BreakOuterLoop:
    pass
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;
#include <stdio.h>
int i,j;
for(i=0;i<sizeof(m)/sizeof(*m);i++)
{
	for(j=0;j<sizeof(*m)/sizeof(**m);j++)
	{
		if(m[i][j]<0)
		{
			printf("%d\n",m[i][j]);
			goto end;
		}
	}
}
end:
(loop [rows m]
  (if-let [v (some #(when (neg? %) %) (first rows))]
    v
    (recur (rest rows))))
#include <iostream>
auto indices = findNegativeValue (m, 10, 20);
std::cout << m[indices.first][indices.second] << '\n';

std::pair<int, int> findNegativeValue (int **m, int rows, int columns) {
  for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
      if (m[i][j] < 0) return make_pair (i, j);
    }
  }
  throw "No negative value!";
}
using System;
foreach (int v in m)
{
    if (v < 0)
    {
        Console.WriteLine(v);
        break;
    }
}
bool keepLooping = true;

for(int i = 0; i < m.length && keepLooping; i++)
{
	for(int j = 0; j < m[i].length && keepLooping; j++)
	{
		if(m[i][j] < 0)
		{
			Console.WriteLine(m[i][j]);
			keepLooping = false;
		}
	}
}
using System;
for (
        int i = 0,
        rows = m.GetLength(0),
        cols = m.GetLength(1); i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        if (m[i, j] < 0)
        {
            Console.WriteLine(m[i, j]);
            i = int.MaxValue - 1; // Break outer loop.
            break;
        }
    }
}
using System;
foreach (int[] row in m)
{
    foreach (int v in row)
    {
        if (v < 0)
        {
            Console.WriteLine(v);
            goto DONE;
        }
    }
}
DONE: ;
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;
		}
	}
}
OUTER: for (var i = 0; i < m.length; i++) {
  for (var j = 0; j < m[i].length; j++) {
    if (m[i][j] < 0) {
      print("Negative value found at $i,$j: ${m[i][j]}");
      break OUTER;
    }
  }
}
  def main([]), do: nil
  def main([row | rows]), do: main(row, rows)
  def main([], rows), do: main(rows)
  def main([number | numbers], rows) when number >= 0, do: main(numbers, rows)
  def main([number | _], _), do: number
find_negative_in([]) -> undefined;
find_negative_in([Row|Rows]) -> find_negative_in(Row, Rows).

find_negative_in([], Rows) -> find_negative_in(Rows);
find_negative_in([Pos|Values], Rows) when Pos >= 0 ->
	find_negative_in(Values, Rows);
find_negative_in([Neg|_], _) -> Neg.
  outer: do j=1, size(m,2)
     do i=1, size(m,1)
        v = m(i,j)
        if (v < 0) then
           print *,v
           exit outer
        end if
     end do
  end do outer
mainloop:
	for i, line := range m {
		for _, v := range line {
			if v < 0 {
				fmt.Println(v)
				break mainloop
			}
		}
	}
(print . head . filter (<0) . concat) m
OUTER:
for (var i in m) {
   for (var j in m[i]) {
      if (m[i][j] < 0) {
         console.log("Negative value found: "+m[i][j]);
         break OUTER;
      }
   }
}
import static java.lang.System.out;
   int i, j, M = m.length, N = m[0].length, x;
a: for (i = 0; i < M; ++i)
       for (j = 0; j < N; ++j)
           if ((x = m[i][j]) < 0) {
               out.println(x);
               break a;
           }
import static java.lang.System.out;
int i, j, M = m.length, N = m[0].length, x;
boolean b = false;
for (i = 0; i < M; ++i) {
    for (j = 0; j < N; ++j)
        if ((x = m[i][j]) < 0) {
            out.println(x);
            b = true;
            break;
        }
    if (b) break;
}
mainloop: for(int i=0;i<m.length;i++)
	for(int j=0;j<m[i].length;j++)
		if(m[i][j]<0){
			System.out.println(m[i][j]);
			break mainloop;
		}
loop@ for (x in 0..7) {
  for (y in 0..7) {
    val v = m[x][y]
    if ( v < 0) {
       println("found a negative value at [$x][$y]: $v")
       break@loop
     }
  }
}
(loop named outer
      for i below (array-dimension m 0)
      do (loop for j below (array-dimension m 1)
               for v = (aref m i j)
               when (minusp v)
               do (progn
                    (print v)
                    (return-from outer))))
for _,v1 in ipairs(m) do
 for _,v2 in ipairs(v1) do
  if v2<0 then
   print(v2)
   goto outer
  end
 end
end
::outer::
breakout = false
for i,v1 in ipairs(m) do
   for j,v2 in ipairs(v1) do
      if v2 < 0 then
         print(v2)
         state = "found"
         breakout = true
         break
      end
   end
   if breakout then break end
end
@import Foundation;
[m enumerateObjectsUsingBlock:^(NSArray *row, NSUInteger rn, BOOL *stopr) {
  [row enumerateObjectsUsingBlock:^(NSNumber *v, NSUInteger cn, BOOL *stopc) {
    if (v.intValue<0) {
      NSLog(@"found %@ at row:%lu col:%lu",v,rn,cn);
      *stopr=*stopc=YES;
      return; // to quit the current block immediately
    }
  }];
}];
for ($y = 0; $y < count($m); $y++) {
    for ($x = 0; $x < count($m[$y]); $x++) {
        if ($m[$y][$x] == $v) {
            break 2;
        }
    }
}
var i,j: integer;
   flag:boolean;
[...]
for i := 0 to length(m) * length(m[0]) - 1 do
begin
  v := m[i mod length(m), i div length(m)];
  if v < 0 then
  begin
    writeln(v);
    break;
  end;
end;

for i := 0 to high(m) do
begin
  for v in m[i] do
  begin
    flag := (v < 0);
    if flag then
    begin
      writeln(v);
      break;
    end;
  end;
  if flag then
    break;
end;
OUTER: for my $row (@m) {
   INNER: for my $v (@$row) {
      if ($v < 0) {
         print "Negative value found: $v\n";
         last OUTER;
      }
   }
}
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: for v in m {
    'inner: for i in v {
        if i < 0 {
            println!("Found {}", i);
            break 'outer;
        }
    }
}
| negativeValue |
negativeValue := [ :matrix || ctx |
    ctx := thisContext sender.
    matrix do: [ :row |
        row do: [ :value |
            (value < 0) ifTrue: [ ctx resumeWith: value ].
        ]
    ]
] value: m. "ex. m := #((1 2 -1 3))"
Transcript show: negativeValue; cr.
Imports System
For i As Integer = 0 To m.GetLength(0) - 1
    For j As Integer = 0 To m.GetLength(1) - 1
        If m(i, j) < 0 Then
            Console.WriteLine(m(i, j))
            i = Integer.MaxValue - 1 ' Break outer loop.
            Exit For
        End If
    Next
Next
Imports System
Select Case Nothing
    Case Else
        For Each row As Integer() in m
            For Each v As Integer In row
                If v < 0 Then
                    Console.WriteLine(v)
                    Exit Select
                End If
            Next
        Next
End Select
Imports System
    For Each row As Integer() in m
        For Each v As Integer In row
            If v < 0 Then
                Console.WriteLine(v)
                GoTo DONE
            End If
        Next
    Next
DONE:
Imports System
Dim colCount As Integer = m(0).Length
For Each row As Integer() In m
    Dim j = 0
    Do While j < colCount
        Dim v = row(j)
        If v < 0 Then
            Console.WriteLine(v)
            Exit For
        End If
        j += 1
    Loop
Next

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