Home  >  Article  >  Backend Development  >  What is the difference between break and continue statements in C#?

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

PHPz
PHPzforward
2023-09-13 19:25:021159browse

The

C# 中的 break 和 continue 语句有什么区别?

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-

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 a 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();
      }
   }
}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete