Break and continue Statements

C# break Sometimes, you want to stop the loop even if the condition is still true. How do you do that? Well, we can use the C# break keyword to stop the loop and the continue keyword to skip one loop cycle and continue to the next. The program below will demonstrate the use of break and continue statements.

using System;

namespace BreakContinueDemo
{
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Demonstrating the use of break.\n");

            for (int x = 1; x < 10; x++)
            {
                if (x == 5)
                    break;

                Console.WriteLine("Number " + x);
            }

            Console.WriteLine("\nDemonstrating the use of continue.\n");

            for (int x = 1; x < 10; x++)
            {
                if (x == 5)
                    continue;

                Console.WriteLine("Number " + x);
            }
        }
    }
}

Example 1 – break and continue Statements

Demonstrating the use of break.

Number 1
Number 2
Number 3
Number 4

Demonstrating the use of continue.

Number 1
Number 2
Number 3
Number 4
Number 6
Number 7
Number 8
Number 9

The program uses a for loop although using break inside while or do while loops will have the same results. When the value of xreaches 5 as the  if condition in line 11 said, then execute the break statement (line 14). The looping is immediately stopped even if the condition x < 10 is still true. On the other hand, the continue  (line 24) only stops the execution for a particular loop cycle. If the value of x is 5 and then the continue  statement executes, it will stop the execution of codes and proceed the next  loop cycle.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *