This language bar is your friend. Select your favorite languages!
Select your favorite languages :
- Or search :
- Ada
- C
- Clojure
- C++
- C#
- C#
- C#
- C#
- D
- Dart
- Elixir
- Erlang
- Fortran
- Go
- Haskell
- JS
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Python
- Python
- Python
- Ruby
- Rust
- Smalltalk
- VB
- VB
- VB
- VB
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;
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.
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.
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.
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.
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;
}
}
}
A straightforward way without using goto is to (if applicable) set the outer loop's iteration variable out of bounds and leave a comment explaining the technique.
foreach (int[] row in m)
{
foreach (int v in row)
{
if (v < 0)
{
Console.WriteLine(v);
goto DONE;
}
}
}
DONE: ;
In this case, m is int[][], an array of arrays, so foreach loops can be used.
foreach loops have no out-of-bounds condition; goto becomes the clearest alternative to extracting the loops into a method.
foreach loops have no out-of-bounds condition; goto becomes the clearest alternative to extracting the loops into a method.
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.
Assuming the matrix is implemented as a list of lists.
We just use a recursive function that instead of printing the value, just returns it.
We just use a recursive function that instead of printing the value, just returns it.
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;
}
}
}
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."
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.
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
1) First break breaks out of the inner-loop. Second break breaks out of the outer-loop.
2) Simplifying is possible. Change line 11 in if (state == "found") then break end and remove lines 1 and 7.
3) No goto-statement.
4) As Nepta wrote: using a function might be another solution, as an example see http://www.programming-idioms.org/idiom/20/return-two-values/1661/lua
2) Simplifying is possible. Change line 11 in if (state == "found") then break end and remove lines 1 and 7.
3) No goto-statement.
4) As Nepta wrote: using a function might be another solution, as an example see http://www.programming-idioms.org/idiom/20/return-two-values/1661/lua
[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
}
}];
}];
Showing an imperfect work-around with blocks. If blocks are not used, goto is available: check the plain C idiom for an example. Note it might be tempting to use exceptions instead; do not: in ObjC it is considered a bad practice
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;
2 Solutions:
1. do it with one loop.
2. Break both loops with a flag.
1. do it with one loop.
2. Break both loops with a flag.
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
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.
This will raise StopIteration if it doesn't find the value so we need to account for it.
| 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.
Normally, you would use non-local return inside a method containing just the outer loop.
thisContext allows access and manipulation of the call stack. It can be used to implement continuations, which is what the example does.
thisContext allows access and manipulation of the call stack. It can be used to implement continuations, which is what the example does.
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
The Exit statement breaks the innermost block of the type specified. To avoid GoTo for dubious benefit in readability, the loops can be surrounded by a dummy block that does not affect control flow which is then exited out of when the element is found.
Select Case is used here as it cannot be confused with the loops and is relatively uncommon.
Select Case is used here as it cannot be confused with the loops and is relatively uncommon.
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
In this case, m is Integer()() and the inner For loop is implemented manually as a Do loop; all inner arrays are assumed to have the same length.
The Exit statement requires the name of the type of construct being exited and breaks the innermost statement of the same type as specified: in this case, the outer loop.
The Exit statement requires the name of the type of construct being exited and breaks the innermost statement of the same type as specified: in this case, the outer loop.
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:
In this case, m is Integer()(), an array of arrays, so For Each loops can be used.
For Each loops have no out-of-bounds condition; GoTo becomes the clearest alternative to extracting the loops into a method.
For Each loops have no out-of-bounds condition; GoTo becomes the clearest alternative to extracting the loops into a method.
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
A straightforward way without using GoTo is to (if applicable) set the outer loop's iteration variable out of bounds and leave a comment explaining the technique.