Logo

Programming-Idioms

  • C++
  • Java
  • Dart

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
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;
    }
  }
}
#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.
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;
		}

mainloop is a label used to refer to the outer loop.
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;
           }

"... The break statement terminates the labeled statement ... Control flow is transferred to the statement immediately following the labeled (terminated) statement."
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