Csharp 简明教程

C

在需要多次执行代码块时,可能会出现一种情况。通常,语句按顺序执行:函数中的第一个语句先执行,然后执行第二个语句,依此类推。

There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

编程语言提供了各种控制结构,允许执行更复杂的路径。

Programming languages provide various control structures that allow for more complicated execution paths.

循环语句允许我们执行一个语句或一组语句多次,以下是大多数编程语言中的循环语句的一般格式 -

A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages −

loop architecture

C# 提供了以下类型的循环来处理循环要求。单击以下链接以查看其详细信息。

C# provides following types of loop to handle looping requirements. Click the following links to check their detail.

Sr.No.

Loop Type & Description

1

while loopIt repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body.

2

for loopIt executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3

do…​while loopIt is similar to a while statement, except that it tests the condition at the end of the loop body

4

nested loopsYou can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements

循环控制语句改变了它在正常序列中的执行。当执行退出一个作用域时,在该作用域中创建的所有自动对象会被销毁。

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C# 提供了以下控制语句。单击以下链接以查看它们的详细信息。

C# provides the following control statements. Click the following links to check their details.

Sr.No.

Control Statement & Description

1

break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2

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

Infinite Loop

如果条件永远不会变为 false,则循环将变成无限循环。 for 循环传统上用于此目的。由于组成 for 循环的三个表达式都不需要,因此你可以通过将条件表达式留空来创建一个无限循环。

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.

Example

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         for (; ; ) {
            Console.WriteLine("Hey! I am Trapped");
         }
      }
   }
}

当条件表达式不存在时,假定为 true。可以有初始化和增量表达式,但程序员更常见地使用 for(;;) 构造来表示无限循环。

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop.