Logo

Programming-Idioms

  • Kotlin
  • C++
  • Python
  • Rust
  • PHP
  • Scala
  • C
  • Pascal

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
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;

2 Solutions:
1. do it with one loop.
2. Break both loops with a flag.
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
     }
  }
}
#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!";
}

Whenever the code is as complicated as you need to break the outer loop, it is the correct time to add a new function.

edit: The above comment is an opinion and adds nothing to presenting a solution to the stated problem. It is a narrow-minded opinion to think such a statement can apply to every conceivable situation.
z = False
for a in m:
    for b in a:
        if z := b < 0:
            print(b)
            break
    if z: break
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

We make a generator that will return negative values from a list (and use chain.from_iterable(matrix) to lazily extract the values) and only take one value from it with the next function. The generator will not continue until we call next again.

This will raise StopIteration if it doesn't find the value so we need to account for it.
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))

Rather than set break flags, it is better to refactor into a function, then use return to break from all nested loops.
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

This is ugly because the pythonic way to solve this problem would be to refactor so that one doesn't have to break out of multiple loops. See PEP3136
'outer: for v in m {
    'inner: for i in v {
        if i < 0 {
            println!("Found {}", i);
            break 'outer;
        }
    }
}

Loop label syntax is similar to lifetimes.
for ($y = 0; $y < count($m); $y++) {
    for ($x = 0; $x < count($m[$y]); $x++) {
        if ($m[$y][$x] == $v) {
            break 2;
        }
    }
}
#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:

only works if m is allocated statically or on the stack, not if allocated in the heap.

edit: the statement above is misleading. It is referring to the use of sizeof() to set up the loops, and has nothing to do with using goto to break the loop. Using goto to break the loop will work as written, regardless of how the variables are allocated.
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