What is the difference between break and continue statements in C#?


The break statement terminates the loop and transfers execution to the statement immediately following the loop.

The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.

The following is the complete code to use continue statement in a while loop −

Example

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         /* local variable definition */
         int a = 10;

         /* loop execution */
         while (a > 20) {
            if (a == 15) {
               /* skip the iteration */
               a = a + 1;
               continue;
            }
            Console.WriteLine("value of a: {0}", a);
            a++;
         }
         Console.ReadLine();
      }
   }
}

The following is an example of break statement −

Example

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;

         /* while loop execution */
         while (a < 20) {
            Console.WriteLine("value of a: {0}", a);
            a++;

            if (a > 15) {
               /* terminate the loop using break statement */
               break;
            }
         }
         Console.ReadLine();
      }
   }
}

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements