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 rest of its body and immediately retest its condition before repeating.
When a break statement is encountered within a loop, the loop terminates immediately and program control is restored at the next statement after the loop.
The continue statement in C# works a bit like a break statement. However, instead of forcing termination, continue forces the next iteration of the loop and skips any code in between.
The following is the complete code for using the continue statement in a while loop-
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 a break statement-
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(); } } }
The above is the detailed content of What is the difference between break and continue statements in C#?. For more information, please follow other related articles on the PHP Chinese website!