C# Loops

Sometimes, you may need to execute the same block of code multiple times. In general, statements are executed sequentially: the first statement in a function executes first, followed by the second statement, and so on.

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

Loop statements allow us to execute a statement or group of statements multiple times. The following is the general form of a loop statement in most programming languages:

循环结构

Loop Types

C# provides the following loop types. Click the link to view details of each type.

Loop TypesDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for/foreach loopExecutes a sequence of statements multiple times and simplifies the code that manages the loop variable.
do...while loopIt is similar to the while statement, except that it tests the condition at the end of the loop body.
Nested LoopsYou can use one or more loops inside a while, for, or do..while loop.

Loop control statements

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

C# provides the following control statements. Click the link to view details of each statement.

Control StatementsDescription
break StatementTerminatelooporswitchStatement — program flow will continue with the next statement immediately following the loop or switch.
continue StatementSkips the current iteration of the loop and begins the next iteration.

Infinite Loop

If the condition is never false, the loop becomes an infinite loop.forA loop can be used to implement an infinite loop in the traditional sense. Since none of the three expressions that form the loop are required, you can leave certain conditional expressions empty to form an infinite loop.

Example

using System;

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

When the conditional expression is absent, it is assumed to be true. You may also set an initial value and an increment expression, but generally programmers prefer the for(;;) structure to represent an infinite loop.

other extensions