Is there a way of specifying which block or loop to break out of when working with nested loops?

The easiest way is to use goto: using System;

class BreakExample

{

public static void Main(String[] args)

{

for(int i=0; i<3; i++)

{

Console.WriteLine("Pass {0}: ", i);

for( int j=0 ; j<100 ; j++ )

{

if ( j == 10) goto done;

Console.WriteLine("{0} ", j);

}

Console.WriteLine("This will not print");

}

done:

Console.WriteLine("Loops complete.");

}

}

Showing Answers 1 - 3 of 3 Answers

venkatesh

  • Oct 13th, 2006
 

In java there is no goto operator.I think we should use label statement for that

  Was this answer useful?  Yes

jmruizsr

  • Sep 18th, 2007
 

Yes, there are ways to break out of nested loops.  Although GOTO is allowed in C#, it is normally a bad idea, bad style, and indication of lack of good software development foundation of those who use it (no offense intended).
Here are a couple of better and cleaner approaches:
1) Use exceptions....You could create a new type of exception
--------------
try
{
   for( int i=0; i<3; i++)
   {
      for( int j=0; j<100; j++)
      {
         if(j>10)
         {
            throw new Exception("Breaking from loop");
         }
      }
   }
}
catch(Exception ex)
{
   // do something here
}
--------------
2) Use a flag....
--------------
int breakFromLoop = 0;

   for( int i=0; breakFromLoop==1 || i<3; i++)
   {
         // do smoething

      for( int j=0; breakFromLoop==1 || j<100; j++)
      {
         // do smoething

         if(j>10)
         {
            breakFromLoop = 1;
            continue;
         }
         // do smoething

      }
      if(breakFromLoop==1)
      {
         continue;
       }

      // do smoething

   }
--------------

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions