...

View Full Version : exiting nested for loops



Spudhead
01-19-2005, 11:02 AM
If I've got the following code for checking whether a number exists within a 3x3 grid:


for rowCount=0 to 2
for colCount=0 to 2
if aWhichGrid(rowCount,colCount) & "" <> "" then
if cInt(aWhichGrid(rowCount,colCount)) = cInt(theNumber) then
rv = false
exit for
end if
end if
next
next


The "exit for" that's there only exits the innermost loop. I want to exit both; the number exists and I don't want to do any more looping. But I can't quite get my head round where to put the second "exit for"?

glenngv
01-19-2005, 01:45 PM
I think there's no counterpart in vbscript for javascript's label. In javascript, you can break out of the outermost loop by specifying a label.


outer:
for (var i=0;i<5;i++) {
for (var j=0;j<5;j++) {
alert(i+","+j);
break outer;
}
}

The quick workaround I can think of in your case is to set the iterator variable used in the outermost loop (rowCount) to a number outside the range.

for rowCount=0 to 2
for colCount=0 to 2
if aWhichGrid(rowCount,colCount) & "" <> "" then
if cInt(aWhichGrid(rowCount,colCount)) = cInt(theNumber) then
rv = false
rowCount=3
exit for
end if
end if
next
next

But if you will use the value of rowCount in the succeeding codes, then you can try this another solution:

for rowCount=0 to 2
for colCount=0 to 2
if aWhichGrid(rowCount,colCount) & "" <> "" then
if cInt(aWhichGrid(rowCount,colCount)) = cInt(theNumber) then
rv = false
exit for
end if
end if
next
if rv = false then exit for
next

avkb03
01-21-2005, 05:06 PM
Why not:



for rowCount=0 to 2
for colCount=0 to 2
if aWhichGrid(rowCount,colCount) & "" <> "" then
if cInt(aWhichGrid(rowCount,colCount)) = cInt(theNumber) then
rv = false
colCount = 2
rowCount = 2
end if
end if
next
next


Is this "grid" actually an array?


If it's an array, you can...



arrString = JOIN(aWhichGrid,";")
If instr(1,arrString, ";" & theNumber & ";") > 0 then
rv = false
end if



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum