nested for loops

  • Thread starter Thread starter dawn
  • Start date Start date
D

dawn

Hi,

Once again I have a question :

In my app, I have nested loops, very basic stuff, like

for (int i = 0; i < 50; i++)
{
for (int j = 0 ; j < 75; j++)
{
if (expression)
{
do something
}
else
{
do something else
}
}
}

What I would like to do, is when I reach "do something else" move on to the
next step of the outer loop.
So i = 2 ; j = 24
I encounter "do something else"
now I want to move on to i = 3

How can I accomplish this?

Thanks
 
Ok, got that wrong, I actually have 3 nested loops and when I encounter "do
something else" in the innermost loop, I want the outermost loop to move on
to the next step.

Thanks.
 
Hm, to step out of one loop you could simply use break, but to step out of
the parent loop too I think you need to set a variable, something like
bool stepOut;

bool stepOut = false;

for (int i = 0; i < 50; i++)
{
for (int j = 0 ; j < 75; j++)
{
for ( int k = 0; k < 100; k++)
{
if (expression)
{
do something
}
else
{
do something else
stepOut = true;
break;
}
}
if(stepOut)
{
stepOut = false;
break;
}
}
}
 
Morten said:
Hm, to step out of one loop you could simply use break, but to step out
of the parent loop too I think you need to set a variable, something
like bool stepOut;

bool stepOut = false;

for (int i = 0; i < 50; i++)
{
for (int j = 0 ; j < 75; j++)
{
for ( int k = 0; k < 100; k++)
{
if (expression)
{
do something
}
else
{
do something else
stepOut = true;
break;
}
}
if(stepOut)
{
stepOut = false;
break;
}
}
}

Either that or use a goto. (horrible practice, btw)


outer_loop:
for (int i = 0; i < 50; i++)
{
for (int j = 0 ; j < 75; j++)
{
if (expression)
{
do something
}
else
{
goto outer_loop;
}
}
}
 
There are three cases, I don't know what you really want to do:
1. increment the outer loop, restart immediately the inner loop: use "break"
( from i=4, j=23 you'll have i=5,j=0 and the execution jumps to the
beggining of the inner loop)

2. increment the outer loop, reset the innner loop without restarting the
inner loop: use "i++; j=-1" ( from i=4, j=23 you'll have i=5,j=-1 the inner
loop continues with j=-1!!!; next on inner loop will be i=5; j=0)

3. increment the outer loop whitout restarting/resetting the inner loop:
"i++" ( from i=4, j=23 you'll have i=5,j=23 with continuation of the inner
loop; next on inner loop will be i=5; j=24)
 
The way to do this "by the book", would be to use a while-loop, wouldn't it?
Like:
int i = 0;
int j;
int k;
bool BreakToOuter = false;
while (i<50)
{
j = 0;
while ((j < 75) && !BreakToOuter)
{
k=0;
while ((k < 100) && !BreakToOuter)
{
if (expression)
{
//Do something
}
else
{
//Do something else
BreakToOuter = true;
}
++k;
}
++j;
}
++i;
BreakToOuter = False;
}

No "GOTO"-style behaviour, but you buy that by some more code.

Scarfeet
 
Back
Top