Software & Finance





C# - Use of Break and Continue statements





break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.

These statements are used in any loop statements (for,do while, while) and switch case statements.

 

The sample code given below has infinite for loop. if i >= 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, event count will not get incremented.

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace BreakContinue

{

   class BreakContinue

   {

      static void Main(string[] args)

      {

          int evencount = 0, i = 0;

          for(i = 0; ; i++)

          {

              if(i >= 60)

                  break; // Terminate the for loop

 

              if((i % 2) != 0)

                  continue; // Will skip the reminder of the for loop

 

              evencount++;

          }

          System.Console.WriteLine("Total Even Numbers Between 0 – 60 is: {0}", evencount);

      }

   }

 

}

Output


 

Total Even Numbers Between 0 – 60 is: 31